Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 380
colin Avatar asked Dec 10 '22 10:12

colin


2 Answers

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.

like image 68
Dota2 Avatar answered Dec 23 '22 17:12

Dota2


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.

like image 34
bcsb1001 Avatar answered Dec 23 '22 16:12

bcsb1001