2

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?

Hank D
6,4993 gold badges28 silver badges36 bronze badges
asked Mar 9, 2017 at 13:07
5
  • Why are you using reduce here? Commented Mar 9, 2017 at 13:15
  • 3
    What do you mean by "all the object"? Commented Mar 9, 2017 at 13:15
  • 2
    Remove the map and reduce and use max instead with an appropriate Comparator that compares by salary. Commented Mar 9, 2017 at 13:15
  • I try to use this 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. Commented Mar 9, 2017 at 13:32
  • 3
    Please, next time, choose a more fitting question title Commented Mar 9, 2017 at 13:38

2 Answers 2

5

Use Stream.max(Comparator<? super T> comparator) method:

Stream.concat(manager.getChild().stream(),
 manager1.getChild().stream())
 .max(Comparator.comparingInt(dev -> dev.getSalary())
answered Mar 9, 2017 at 13:32
Sign up to request clarification or add additional context in comments.

Comments

1

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.

answered Mar 9, 2017 at 13:33

2 Comments

flatMap is overkill here
@ZhekaKozlov but it's more flexible: You can plug this flow on to any stream of managers, eg a List<Employee> via .stream(), or an Employee[] via Arrays.stream() etc. Conversely, hardcoding the stream calls is not scaleable or flexible and breaks DRY

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.