1Z0-819 · Question #182
Given: public class Employee { private String name; private String neighborhood; private LocalDate birthday; private int salary; // ...getters and setters } and List<Employee> roster = new…
The correct answer is D. .collect(Collectors.groupingBy(e -> e.getNeighborhood(), Collectors.collectingAndThen(Collectors.maxBy((x, y) -> x.getSalary() - y.getSalary()), Optional::get))). Option D correctly uses Collectors.groupingBy(e -> e.getNeighborhood(), ...) to group employees by neighborhood, then applies a downstream maxBy collector with the comparator (x, y) -> x.getSalary() - y.getSalary() - which is ascending order, so maxBy correctly selects the…
Question
Options
- A.collect(Collectors.maxBy(Employee::getSalary, Collectors.groupingBy(Comparator.comparing(e -> e.getNeighborhood()))));
- B.collect(Collectors.groupingBy(Employee::getNeighborhood, Collectors.maxBy(Comparator.comparing(Employee::getSalary))));
- C.collect(Collectors.groupingBy(e -> e.getNeighborhood(), Collectors.maxBy((x, y) -> y.getSalary() - x.getSalary())));
- D.collect(Collectors.groupingBy(e -> e.getNeighborhood(), Collectors.collectingAndThen(Collectors.maxBy((x, y) -> x.getSalary() - y.getSalary()), Optional::get)));
How the community answered
(23 responses)- A9% (2)
- B9% (2)
- C4% (1)
- D78% (18)
Explanation
Option D correctly uses Collectors.groupingBy(e -> e.getNeighborhood(), ...) to group employees by neighborhood, then applies a downstream maxBy collector with the comparator (x, y) -> x.getSalary() - y.getSalary() - which is ascending order, so maxBy correctly selects the highest-paid employee in each group. The collectingAndThen wrapper with Optional::get serves as a finisher that unwraps the result after collection.
Why the distractors fail:
- A is structurally wrong -
Collectors.maxByaccepts only aComparator, not aFunctionand anotherCollectoras arguments. - B places the right building blocks but uses
Comparator.comparing(Employee::getSalary)wheregetSalary()returns a primitiveint, which can cause type inference issues -Comparator.comparingIntwould be the safe choice for primitives. - C has the subtraction reversed:
(x, y) -> y.getSalary() - x.getSalary()produces a descending comparator, somaxByactually picks the employee with the lowest salary - the opposite of what's needed.
Memory tip: Think "Group → then Max" - the outer collector is always groupingBy(classifier, downstream), and the downstream is maxBy(comparator). When writing the inline comparator for maxBy, remember x - y = ascending = truly "max"; y - x = descending = traps you into returning the min.
Topics
Community Discussion
No community discussion yet for this question.