Collectors in Java
Sorting with comparators and grouping with keys.
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
var words = List.of("fig", "apple", "cherry", "date", "banana");
var byLength = words.stream()
.sorted(Comparator.comparingInt(String::length))
.toList();
System.out.println(byLength);
// groupingBy builds a map of key -> members in one pass
var groups = words.stream()
.collect(Collectors.groupingBy(String::length));
System.out.println(groups);
var joined = words.stream().collect(Collectors.joining(", "));
System.out.println(joined);
How it works
Comparator.comparingInt(String::length)sorts by a property.groupingBybuilds a map of key to members in one pass.joiningcollapses a stream of strings into one.
Keywords and builtins used here
var
The run, in numbers
- Lines
- 18
- Characters to type
- 529
- Tokens
- 134
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 95 seconds.
Step 2 of 3 in Streams, step 23 of 29 in Language basics.