π Day 22 β Optional, Method References & Advanced Streams
β What I learned today
-
Container object to avoid null checks
-
Optional.ofNullable(), ifPresent(), orElse(), orElseThrow()
Optional opt = Optional.ofNullable(getName()); String name = opt.orElse("Guest");
Shortcut for lambdas
Types: Static (Math::max), Instance (System.out::println), Constructor (Employee::new)
-
Collectors.groupingBy(Function) β groups into Map<K, List>
-
Collectors.groupingBy(Function, downstream collector) β group + count/average
// Group employees by department
Map<String, List> byDept = employees.stream() .collect(Collectors.groupingBy(Employee::getDepartment));
// Count per department
Map<String, Long> counts = employees.stream() .collect(Collectors.groupingBy(Employee::getDepartment, Collectors.counting()));
// Average salary per department Map<String, Double> avgSalary = employees.stream() .collect(Collectors.groupingBy(Employee::getDepartment, Collectors.averagingDouble(Employee::getSalary)));