Member-only story
8 Advanced Stream API Tips You Should Know
3 min read 4 days ago
Java Streams API was introduced with Java 8. It allowed us to write clean, concise and readable code.
Here are 8 coding tips related to Streams API that you should use to enhance your development experience.
My articles are free for everyone. Non-members can read this full article for free HERE.
1. Group and Transform in One Pass
Old Code
Map<String, List<String>> grouped = list.stream()
.collect(Collectors.groupingBy(
s -> s.substring(0, 1)));
for (Map.Entry<String, List<String>> e : grouped.entrySet()) {
e.setValue(e.getValue().stream().map(String::toUpperCase).collect(Collectors.toList()));
}
Refactored Code
Map<String, List<String>> grouped = list.stream()
.collect(Collectors.groupingBy(
s -> s.substring(0, 1),
Collectors.mapping(String::toUpperCase, Collectors.toList())));
Using teeing() Collector for Dual Accumulation
This method is available in Java 12+. It avoids double iterations with sum() and average() separately, as shown in the below code.
Code: Get Sum and Average in one Pass
Map.Entry<Integer, Double> result =…