Java中查找List中最大值的元素

x33g5p2x  于9个月前 转载在 Java  
字(1.7k)|赞(0)|评价(0)|浏览(107)

在 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]

相关文章

热门文章

更多