Harsh Mishra
Harsh Mishra

Reputation: 2135

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. It could be better if using a stream. Output will be the "set" object with contains the Character.

Upvotes: 4

Views: 5196

Answers (3)

Eugene
Eugene

Reputation: 120858

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

Upvotes: 7

Michael
Michael

Reputation: 44150

String has a method which will give you a stream of characters. It's actually an IntStream so we just need to convert them to Characters and then collect to a set.

"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.

Upvotes: 14

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

I think this is the simplest way, preserving the requirement of using a 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));

Upvotes: 5

Related Questions