MST

星途 面试题库

面试题:Java Stream limit方法在复杂数据结构处理场景的运用

给定一个List<Map<String, Object>>,其中每个Map代表一个员工的信息,包含'name'(姓名)、'age'(年龄)、'salary'(薪资)等键值对。请使用Java Stream的limit方法,找出薪资最高的前3名员工,并返回他们的姓名和年龄组成的新List<Map<String, Object>>,需考虑性能优化,写出代码实现。
25.9万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
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);
    }
}

解释:

  1. employees.stream():将List<Map<String, Object>>转换为流。
  2. .sorted((e1, e2) -> ((Number) e2.get("salary")).intValue() - ((Number) e1.get("salary")).intValue()):根据薪资对员工信息进行降序排序,这里直接通过get("salary")获取薪资值并转换为Number类型来比较,性能较好,避免了复杂的自定义比较器实现。
  3. .limit(3):取薪资最高的前3名员工。
  4. .map(employee -> Map.of("name", employee.get("name"), "age", employee.get("age"))):将每个员工的信息映射为只包含姓名和年龄的新Map
  5. .collect(Collectors.toList()):将流转换回List<Map<String, Object>>