简体   繁体   English

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

[英]How to convert a String to a Java 8 Stream of Characters?

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

Correction: As you guys pointed, I was using Java 7. Now the method chars() is there.更正:正如你们所指出的,我使用的是 Java 7。现在方法chars()就在那里。 But the question still applies:但问题仍然适用:

How can I get a Stream<Character> from a String?如何从字符串中获取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.另一个答案也提供了有用的信息。

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.如果需要char值,可以使用String.chars()返回的IntStream并将int值转换为char而不丢失信息。 The other answers explained why there's no CharStream primitive specialization for the Stream class.其他答案解释了为什么Stream类没有CharStream原始专业化。

If you really want boxed Character objects, then use mapToObj() to convert from IntStream to a stream of reference type.如果你真的想要装箱的Character对象,那么使用mapToObj()IntStream转换为引用类型的流。 Within mapToObj() , cast the int value to char .mapToObj() ,将int值转换为char Since an object is expected as a return value here, the char will be autoboxed into a Character .由于这里期望对象作为返回值,因此char将被自动装箱为Character This results in Stream<Character> .这导致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

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();
    }
}

I'm late with another approach using Pattern method: splitAsStream()我迟到了使用Pattern方法的另一种方法: splitAsStream()

String test = "Lobgasex loga nepe co so x";

List<Character> chars = Pattern.compile("").splitAsStream(test)
    .map(i -> i.charAt(0))
    .collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM