代码之家  ›  专栏  ›  技术社区  ›  Harsh Mishra

使用流Java8将字符串转换为集合<Character>

  •  0
  • Harsh Mishra  · 技术社区  · 7 年前
    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)));
     }
    

    我想把这个for循环转换成java8的方式。如果使用流,效果会更好。输出将是包含字符的“set”对象。

    3 回复  |  直到 7 年前
        1
  •  11
  •   Michael    7 年前

    String 有一个方法可以给你一个字符流。它实际上是一个 IntStream 所以我们只需要把它们转换成 Character 然后呢 collect 到一组。

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

    TreeSet::new 作为 others 有 shown 如果您需要对集合进行排序。

        2
  •  7
  •   Michael    7 年前
     IntStream.range(0, ALPHABET.length())
              .mapToObj(ALPHABET::charAt)
              .collect(Collectors.toCollection(TreeSet::new));
    
        3
  •  5
  •   Óscar López    7 年前

    我认为这是最简单的方法,保留了使用 TreeSet . 注意,不需要使用 索引 ,可以直接对其字符进行迭代。

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