面试题答案
一键面试import java.util.*;
import java.util.stream.Collectors;
public class EmployeeSalaryRanking {
public static void main(String[] args) {
List<Map<String, Object>> employees = Arrays.asList(
Map.of("name", "Alice", "age", 30, "salary", 8000),
Map.of("name", "Bob", "age", 35, "salary", 9000),
Map.of("name", "Charlie", "age", 28, "salary", 8500),
Map.of("name", "David", "age", 40, "salary", 9500),
Map.of("name", "Eve", "age", 32, "salary", 8200)
);
List<Map<String, Object>> top3Employees = employees.stream()
.sorted((e1, e2) -> ((Number) e2.get("salary")).intValue() - ((Number) e1.get("salary")).intValue())
.limit(3)
.map(employee -> Map.of("name", employee.get("name"), "age", employee.get("age")))
.collect(Collectors.toList());
System.out.println(top3Employees);
}
}
解释:
employees.stream()
:将List<Map<String, Object>>
转换为流。.sorted((e1, e2) -> ((Number) e2.get("salary")).intValue() - ((Number) e1.get("salary")).intValue())
:根据薪资对员工信息进行降序排序,这里直接通过get("salary")
获取薪资值并转换为Number
类型来比较,性能较好,避免了复杂的自定义比较器实现。.limit(3)
:取薪资最高的前3名员工。.map(employee -> Map.of("name", employee.get("name"), "age", employee.get("age")))
:将每个员工的信息映射为只包含姓名和年龄的新Map
。.collect(Collectors.toList())
:将流转换回List<Map<String, Object>>
。