Java- Find the element in the List having maximum value
In Java 8, Stream
API’s max
method returns the maximum element of this stream according to the provided Comparator
and the filter
method returns the elements of this stream that match the given predicate(condition)
.
Test Case: We have a list of employees and our task is to find the employee details having a maximum salary.
1. Find the maximum salary.
int maxSalary = employees.stream()
.map(Employee::getSalary)
.max(Integer::compare).get();
2. Filter the employee on the basis of maximum salary.
Stream<Employee> employee = employees.stream()
.filter(emp -> emp.getSalary() == maxSalary);
See the complete example.
Employee.java
package org.websparrow;
public class Employee {
// Generate Getters and Setters...
private long id;
private String name;
private int salary;
private String department;
public Employee(long id, String name, int salary, String department) {
this.id = id;
this.name = name;
this.salary = salary;
this.department = department;
}
@Override
public String toString() {
return "Employee [id=" + id + ","
+ " name=" + name + ","
+ " salary=" + salary + ","
+ " department=" + department + "]";
}
}
FindEmployee.java
package org.websparrow;
import java.util.Arrays;
import java.util.List;
public class FindEmployee {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee(101, "Manish", 5000, "IT"),
new Employee(109, "Atul", 3000, "HR"),
new Employee(111, "Santosh", 4400, "IT"),
new Employee(109, "Rupendra", 3200, "FIN")
);
// return max salary
int maxSalary = employees.stream()
.map(Employee::getSalary)
.max(Integer::compare).get();
System.out.println("Max salary of the employee:" + maxSalary);
System.out.print("Employee details:");
//filter the employee having max salary
employees.stream()
.filter(emp -> emp.getSalary() == maxSalary)
.forEach(System.out::println);
}
}
Output:
Max salary of the employee:5000
Employee details:Employee [id=101, name=Manish, salary=5000, department=IT]