You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// Group by single fieldMap<String, List<Employee>> byDept =
employees.stream().collect(Collectors.groupingBy(Employee::getDept));
// Group with countingMap<String, Long> countByDept =
employees.stream().collect(Collectors.groupingBy(Employee::getDept, Collectors.counting()));
// Group with sum/averageMap<String, Double> avgSalaryByDept =
employees.stream().collect(Collectors.groupingBy(Employee::getDept,
Collectors.averagingDouble(Employee::getSalary)));
// Sort map by valueMap<String, Integer> sorted = map.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new));
// Top N from mapList<String> topKeys = map.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.limit(3)
.map(Map.Entry::getKey)
.toList();
π― Common Problem Patterns
Pattern 1: Frequency Analysis
// Template for any frequency analysisMap<T, Long> frequency = collection.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Pattern 2: Group-Aggregate-Filter
// Template for group-aggregate-filter operationsMap<String, Double> result = items.stream()
.collect(Collectors.groupingBy(Item::getCategory,
Collectors.summingDouble(Item::getValue)))
.entrySet().stream()
.filter(entry -> entry.getValue() > threshold)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
// Use primitive streams for numbersIntStream.range(0, 1000).sum(); // Better than Stream<Integer>// Parallel streams for large datasetslargeList.parallelStream().filter(predicate).count();
// Avoid multiple terminal operationsList<String> result = stream.collect(Collectors.toList()); // Create once, use multiple times
Memory Optimization
// Use StringBuilder for string buildingStringBuildersb = newStringBuilder();
strings.forEach(sb::append);
// Lazy evaluation - streams don't execute until terminal operationStream<String> lazy = list.stream().filter(expensive_operation); // Not executed yetList<String> result = lazy.toList(); // Now executed