在 Java 8 中,Stream
API 的 max
方法根据提供的 Comparator
返回此流的最大元素,filter
方法返回这个流匹配给定的 predicate(*condition*)
。
测试用例: 我们有一个员工列表,我们的任务是找到具有最高工资的员工详细信息。
1. 找出最高工资。
int maxSalary = employees.stream()
.map(Employee::getSalary)
.max(Integer::compare).get();
2. 根据最高工资筛选员工。
Stream<Employee> employee = employees.stream()
.filter(emp -> emp.getSalary() == maxSalary);
请参阅完整示例。
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 + "]";
}
}
查找员工.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);
}
}
输出:
Max salary of the employee:5000
Employee details:Employee [id=101, name=Manish, salary=5000, department=IT]
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.websparrow.org/java/java-find-the-element-in-the-list-having-maximum-value
内容来源于网络,如有侵权,请联系作者删除!