Coding Techniques
Streams API · Study material
Advanced collectors: nested grouping, collectingAndThen, teeing
Collectors can be nested to build multi-level reports, post-processed with collectingAndThen, or run side by side with teeing.
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.stream.Collectors;
record Sale(String region, String product, int qty, double price) {
double total() { return qty * price; }
}
public class Main {
public static void main(String[] args) {
List<Sale> sales = List.of(new Sale("North", "Pen", 100, 10), new Sale("South", "Book", 20, 150), new Sale("North", "Book", 10, 150),
new Sale("South", "Pen", 300, 10), new Sale("West", "Bag", 5, 900), new Sale("North", "Bag", 2, 900));
// Nested grouping: region → product → total revenue
Map<String, Map<String, Double>> byRegion = sales.stream().collect(Collectors.groupingBy(Sale::region, TreeMap::new,
Collectors.groupingBy(Sale::product, TreeMap::new, Collectors.summingDouble(Sale::total))));
System.out.println(byRegion);
// Best sale per region, unwrapped from Optional with collectingAndThen
Map<String, String> best = sales.stream().collect(Collectors.groupingBy(Sale::region, TreeMap::new,
Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparingDouble(Sale::total)), o -> o.map(Sale::product).orElse("-"))));
System.out.println(best);
// teeing (Java 12): two collectors at once, then combine
String summary = sales.stream().collect(Collectors.teeing(
Collectors.summingDouble(Sale::total), Collectors.counting(), (sum, n) -> "revenue " + sum + " from " + n + " sales"));
System.out.println(summary);
Optional<String> topProduct = sales.stream().collect(Collectors.groupingBy(Sale::product, Collectors.summingInt(Sale::qty)))
.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey);
System.out.println(topProduct.orElse("-"));
}
}
{North={Bag=1800.0, Book=1500.0, Pen=1000.0}, South={Book=3000.0, Pen=3000.0}, West={Bag=4500.0}}
{North=Bag, South=Book, West=Bag}
revenue 14800.0 from 6 sales
PenParallel streams – use with care
// Parallel streams split the work across CPU cores (the common ForkJoinPool)
long primes = IntStream.rangeClosed(2, 5_000_000).parallel().filter(Main::isPrime).count();
// ✔ Good candidates: large data, CPU-heavy, independent elements, no shared mutable state
// ✘ Avoid: small lists, I/O, ordering requirements, side effects:
List<Integer> unsafe = new ArrayList<>();
IntStream.range(0, 1000).parallel().forEach(unsafe::add); // ✘ data race: wrong size or exception
List<Integer> safe = IntStream.range(0, 1000).parallel().boxed().toList(); // ✔ let the stream build the result
// forEach on a parallel stream does not keep order; use forEachOrdered if order matters. Loop to stream: common translations
// count matching for … if … count++ → list.stream().filter(p).count()
// transform for … out.add(f(x)) → list.stream().map(f).toList()
// sum of a property for … total += o.amount() → list.stream().mapToDouble(Order::amount).sum()
// find first for … if … return x → list.stream().filter(p).findFirst()
// any / all for … if … return true → anyMatch(p) / allMatch(p)
// group map.computeIfAbsent(k, …).add → collect(groupingBy(keyFn))
// join strings StringBuilder + separator → map(String::valueOf).collect(joining(", "))
// distinct, sorted Set + sort → distinct().sorted()
// nested loops for a … for b … → flatMap(a -> bs.stream().map(b -> …)) Streams checklist
- Keep each step simple; one operation per line.
- Prefer method references (Order::amount) where they read well.
- Avoid side effects; build results with collect or toList.
- Use primitive streams for numeric work.
- Handle Optional results explicitly.
- Pass a map factory (TreeMap::new) to groupingBy/toMap when order matters.
- Give toMap a merge function if keys can repeat.
- Use parallel() only after measuring.