Skip to content
The Code Storm
All videos
Stream StormPart 2 of 6

Java reduce() and groupingBy() Explained Visually | Stream Storm Part 2

distinct drops repeats, limit stops early, reduce folds a list into one value, and groupingBy sorts items into buckets by a key.

The code from the video

java
List<Integer> nums = List.of(4, 1, 4, 7, 1, 9);
 
nums.stream().distinct().toList();          // [4, 1, 7, 9]
nums.stream().limit(3).toList();            // [4, 1, 4]
nums.stream().reduce(0, Integer::sum);      // 26
java
List<String> words = List.of("ant", "bee", "deer", "cat", "goat");
 
Map<Integer, List<String>> byLength = words.stream()
    .collect(Collectors.groupingBy(String::length));
// {3=[ant, bee, cat], 4=[deer, goat]}

Next in the series

This toMap() Call Crashes Your Java Code (and the Fix) | Stream Storm Part 3

Read the write-up