Java 8 (LTS) · Topic 6 of 12
Grouping and collectors
Definition​
Collectors turn a stream into a result. groupingBy splits items into groups, counting counts them, joining builds one string, and toMap builds a map.
Example code​
Group words by length, count them, and join them
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class Demo {
public static void main(String[] args) {
List<String> words = List.of("java", "go", "rust", "c", "python", "sql");
Map<Integer, List<String>> byLength = words.stream()
.collect(Collectors.groupingBy(String::length));
System.out.println(byLength);
Map<Integer, Long> counts = words.stream()
.collect(Collectors.groupingBy(String::length, Collectors.counting()));
System.out.println(counts);
System.out.println(words.stream().collect(Collectors.joining(", ", "[", "]")));
}
}
// Output:
// {1=[c], 2=[go], 3=[sql], 4=[java, rust], 6=[python]}
// {1=1, 2=1, 3=1, 4=2, 6=1}
// [java, go, rust, c, python, sql]
Finished this page? Track your progress (saved only in your browser).