如何将字符串转换为Java 8字符流? [英] How to convert a String to a Java 8 Stream of Characters?
问题描述
我找到了这个问题关于从java String获取java.util.streams.IntStream但是我现在还没有找到这个方法,因为我正在使用Java 8.
I found this question about getting a java.util.streams.IntStream from a java String but I have not found this method now that I'm using Java 8.
更正:当你伙计们指出,我使用的是Java 7.现在方法 chars()
就在那里。但问题仍然存在:
Correction: As you guys pointed, I was using Java 7. Now the method chars()
is there. But the question still applies:
如何从字符串中获取 Stream< Character>
?
推荐答案
我打算指教你我的关于这个主题的早期回答但事实证明你已经链接到那个问题。 其他答案也提供了有用的信息。
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
这篇关于如何将字符串转换为Java 8字符流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!