简体   繁体   English

将字符串转换为集合 <Character> 使用Stream Java 8

[英]Convert a String into a set<Character> using a Stream java 8

private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
SortedSet<Character> set= new TreeSet<Character>();
for (int i = 0; i < ALPHABET.length(); i++) {
    set.add(new Character(ALPHABET.charAt(i)));
 }

I would like to convert this for loop in Java 8 way. 我想以Java 8方式将此for循环转换。 It could be better if using a stream. 如果使用流,可能会更好。 Output will be the "set" object with contains the Character. 输出将是包含字符的“设置”对象。

String has a method which will give you a stream of characters. String具有一种可以为您提供字符流的方法。 It's actually an IntStream so we just need to convert them to Character s and then collect to a set. 它实际上是一个IntStream因此我们只需要将它们转换为Character ,然后collect到一个集合即可。

"foo".chars()
    .mapToObj(chr -> (char) chr) // autoboxed to Character
    .collect(Collectors.toSet());

or use TreeSet::new as others have shown if you need the set to be sorted. 或使用TreeSet::new其他 显示的那样),如果您需要对集合进行排序。

 IntStream.range(0, ALPHABET.length())
          .mapToObj(ALPHABET::charAt)
          .collect(Collectors.toCollection(TreeSet::new));

I think this is the simplest way, preserving the requirement of using a TreeSet . 我认为这是最简单的方法,可以保留使用TreeSet的要求。 Notice that there's no need to iterate over the input string using indexes , you can directly iterate over its characters. 请注意,无需使用索引来遍历输入字符串,您可以直接遍历其字符。

SortedSet<Character> set =
    ALPHABET.chars()
            .mapToObj(c -> (char) c)
            .collect(Collectors.toCollection(TreeSet::new));

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

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