更新时间:2023-09-26 22:36:34
我打算指教你我的关于这个主题的早期回答但事实证明你已经链接到那个问题。 其他答案也提供了有用的信息。
I was going to point you to my earlier answer on this topic but it turns out that you've already linked to that question. The other answer also provides useful information.
如果你想要的话 char
值,您可以使用 String.chars()$返回的
IntStream
c $ c>并将 int
值转换为 char
而不会丢失任何信息。其他答案解释了为什么 Stream
类没有 CharStream
原始专门化。
If you want char
values, you can use the IntStream
returned by String.chars()
and cast the int
values to char
without loss of information. The other answers explained why there's no CharStream
primitive specialization for the Stream
class.
如果你真的想要盒装的 Character
对象,那么使用 mapToObj()
来转换 IntStream
到引用类型的流。在 mapToObj()
中,将 int
值转换为 char
。由于此处的对象需要作为返回值,因此 char
将自动装箱到字符
中。这导致 Stream< Character>
。例如,
If you really want boxed Character
objects, then use mapToObj()
to convert from IntStream
to a stream of reference type. Within mapToObj()
, cast the int
value to char
. Since an object is expected as a return value here, the char
will be autoboxed into a Character
. This results in Stream<Character>
. For example,
Stream<Character> sch = "abc".chars().mapToObj(i -> (char)i);
sch.forEach(ch -> System.out.printf("%c %s%n", ch, ch.getClass().getName()));
a java.lang.Character
b java.lang.Character
c java.lang.Character