Using .max() with .stream() on a List<>

Viewed 4070

I would like to ask for an explanation to some code that I was given as a solution to an exercise I am doing in a Java course. The exercise is I have a List<>of Employees with various properties(Salary, Name, Surname, E-mail...) and I am trying to retrieve the highest paid employee and print their Name and Salary.

I was able to retrieve the highest Salary but not the Name of the employee, like this:

Integer maxSalary;
maxSalary = roster
    .stream()
    .map(Employee :: getSalary)
    .collect(Collectors.reducing(Integer :: max)
    .get();

I was then given this small block of code and it works completely fine yet i am not quite sure why it works:

Integer maxSalary;
Employee emp2 = roster
    .stream()
    .max((p1, p2) -> Integer.compare(p1.getSalary(), p2.getSalary()))
    .get();
System.out.println("The employee who earns the most is :" + emp2.getName + " and earns : " + emp2.getSalary + " a month.");

I understand it is a Lambda expression using .max i just cant seem to get my head around why and how it works?

5 Answers
Related