Reputation: 2135
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
Reputation: 120858
IntStream.range(0, ALPHABET.length())
.mapToObj(ALPHABET::charAt)
.collect(Collectors.toCollection(TreeSet::new));
Upvotes: 7
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 Character
s 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
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