如何将字符串转换为 Java 8 字符流?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26320910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:13:45  来源:igfitidea点击:

How to convert a String to a Java 8 Stream of Characters?

javajava-8java-stream

提问by ElderMael

I found this questionabout 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 String 获取 java.util.streams.IntStream 的问题,但是我现在使用的是 Java 8 还没有找到这个方法。

Correction: As you guys pointed, I was using Java 7. Now the method chars()is there. But the question still applies:

更正:正如你们所指出的,我使用的是 Java 7。现在方法chars()就在那里。但问题仍然适用:

How can I get a Stream<Character>from a String?

如何Stream<Character>从字符串中获取 a ?

采纳答案by Stuart Marks

I was going to point you to my earlier answeron this topic but it turns out that you've already linked to that question. The other answeralso provides useful information.

我打算向您指出我之前关于此主题的回答,但事实证明您已经链接到该问题。在对方的回答也提供了有用的信息。

If you want charvalues, you can use the IntStreamreturned by String.chars()and cast the intvalues to charwithout loss of information. The other answers explained why there's no CharStreamprimitive specialization for the Streamclass.

如果需要char值,可以使用IntStream返回的 byString.chars()并将int值转换为 ,char而不会丢失信息。其他答案解释了为什么该类没有CharStream原始专业化Stream

If you really want boxed Characterobjects, then use mapToObj()to convert from IntStreamto a stream of reference type. Within mapToObj(), cast the intvalue to char. Since an object is expected as a return value here, the charwill be autoboxed into a Character. This results in Stream<Character>. For example,

如果您确实想要装箱Character对象,则使用mapToObj()将 from 转换IntStream为引用类型的流。在 内mapToObj(),将int值转换为char。由于这里期望对象作为返回值,因此char将被自动装箱为Character. 这导致Stream<Character>. 例如,

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

回答by dds

Please make sure that you are using JDK 8. This method located in CharSequence interface, implemented by String.

请确保您使用的是 JDK 8。该方法位于 CharSequence 接口中,由 String 实现。

This snippet works fine:

这个片段工作正常:

import java.util.stream.IntStream;

public class CharsSample {

    public static void main(String[] args) {
        String s =  "123";
        IntStream chars = s.chars();
    }
}