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

  • A+
Category:Languages
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.

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: