I have this simple instruction
Stream.concat(manager.getChild().stream(),
manager1.getChild().stream())
.map(dev -> dev.getSalary())
.reduce(0, Integer::max);
that concats two List and return the developer that earning more. This returns the maximum salary of the objects in the stream, but how can I retrieve the object that has the maximum salary?
2 Answers 2
Use Stream.max(Comparator<? super T> comparator)
method:
Stream.concat(manager.getChild().stream(),
manager1.getChild().stream())
.max(Comparator.comparingInt(dev -> dev.getSalary())
Comments
Unfortunately you can't reach back to a previous step to get the stream element that provided the maximum salary; you have to compare the elements by an attribute.
To find the subordinate with the highest salary:
Employee max = Stream.of(manager, manager1)
.map(Employee::getChild)
.flatMap(Collection::stream)
.max(Comparators.comparing(Employee::getSalary))
.orElse(null);
I have assumed a class of Employee
so method references can be used, and also refactored the code to a IMHO more usable/standard approach of starting by streaming the managers.
2 Comments
flatMap
is overkill hereList<Employee>
via .stream()
, or an Employee[]
via Arrays.stream()
etc. Conversely, hardcoding the stream calls is not scaleable or flexible and breaks DRY
reduce
here?map
andreduce
and usemax
instead with an appropriateComparator
that compares by salary.Employee rich = Stream.concat(manager.getChild().stream(), manager1.getChild().stream()) .max((dev1, dev2) -> Integer.max(dev1.getSalary(), dev2.getSalary())).get();
but not work very well.