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); // 26java
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
- Stream Storm2 min read
Java Streams: distinct, limit, reduce and groupingBy
Remove repeats, stop early, fold a list into one value, and sort items into groups, with the output of every example.
Related videos
- Short
Stream StormJava Streams Explained Visually: filter, map, flatMap, sorted | Stream Storm Part 1
· Part 1 of 6