4 Replies - 166 Views - Last Post: 12 June 2019 - 08:58 AM Rate Topic: -----

#1 overwhelmed_student   User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 71
  • Joined: 10-May 18

Stream() reduce find max

Posted 12 June 2019 - 05:49 AM

Hey guys,
I have already seen how great reduce() can be if you know how to use it and I am trying to do something with it to understand it better. I have a class Employee (simply what is needed):
class Employee {
   double salary;
}


And I am trying to find the highest paid employee with reduce. I tried t find the Employee first with the highest salary, but this is not working:
public Empoyee findBestPaid(List<Employee> employees) {
   Optional<Double> highesSalary = employees.stream().reduce(Double::max);
   
   //and then here just find the employee with that salary in the stream but I didn't even get that far because there is always an error
}


How can I do that? The salary is a variable and I don't know how to acess that and then find the biggest number.

Is This A Good Question/Topic? 0
  • +

Replies To: Stream() reduce find max

#2 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3638
  • View blog
  • Posts: 16,706
  • Joined: 20-September 08

Re: Stream() reduce find max

Posted 12 June 2019 - 06:40 AM

One way:

return employees.stream().max(Comparator.comparing(Employee::getSalary));


(returns Optional<Employee>)
Was This Post Helpful? 1
  • +
  • -

#3 overwhelmed_student   User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 71
  • Joined: 10-May 18

Re: Stream() reduce find max

Posted 12 June 2019 - 07:09 AM

View Postg00se, on 12 June 2019 - 06:40 AM, said:

(returns Optional<Employee>)

And would there be a way to convert an Optional<Employee> to Employee? I know that this is possible with for example Double or Integer but for a class that I implemented myself?
Was This Post Helpful? 0
  • +
  • -

#4 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3638
  • View blog
  • Posts: 16,706
  • Joined: 20-September 08

Re: Stream() reduce find max

Posted 12 June 2019 - 07:40 AM

return employees.stream().max(Comparator.comparing(Employee::getSalary)).orElseThrow(NoSuchElementException::new);


will get you the pure class instance
Was This Post Helpful? 1
  • +
  • -

#5 overwhelmed_student   User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 71
  • Joined: 10-May 18

Re: Stream() reduce find max

Posted 12 June 2019 - 08:58 AM

View Postg00se, on 12 June 2019 - 07:40 AM, said:

return employees.stream().max(Comparator.comparing(Employee::getSalary)).orElseThrow(NoSuchElementException::new);

Oh, so it is not optional anymore because it is either an Employee or an Exception? I can't be "empty" anymore? Thank you so much!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1