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?
Optional<T> max(Comparator<? super T> comparator)
explains it all.
Since intent of the question was to find the employee with the highest salary, stream is passed directly to .max
which consumes an employee comparator
. Since comparator
is functional interface, it can be passed in as lambda.
.max
is already implemented version of more general reduce
and collect
operation available since java 8
Integer.compare
compares two int numerically. Therefore the .max()
returns the employee with the highest salary.
On the other hand your attempt is specifically trying to get the highest salary.
Cheers. Happy streaming.
The Stream#max
function:
Returns the maximum element of this stream according to the provided Comparator. This is a special case of a reduction.
As Comparator
is a functional interface with only compare(T o1, T o2)
to implement, it may be represented with a lambda. Here, the lambda (p1, p2) -> Integer.compare(p1.getSalary(), p2.getSalary())
compares the salary of p1
with the salary of p2
using standard integer comparison. Therefore, the result will be the Employee
with the largest salary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With