【问题标题】:Java 8 Stream api for selecting top 3 employee name sorted by salary for each department [duplicate]Java 8 Stream api用于选择每个部门按薪水排序的前3名员工姓名[重复]
【发布时间】:2020-02-26 18:12:10
【问题描述】:

我有地图 Map<String, List<employee>> empMap 。作为部门的键和作为关联员工列表的值。我想使用 java 流 API 打印每个部门薪水最高的前 3 名员工。

【问题讨论】:

  • 到目前为止您尝试过什么?分享Employee和Department的代码和结构
  • 如果有两个或多个员工的薪水相同,并且该薪水是三个最高薪水之一,会发生什么情况?

标签: java java-stream


【解决方案1】:
empMap.stream().sorted(-> {/*sorting*/}).limit(3);

【讨论】:

    【解决方案2】:

    将流用于地图的价值而不是原始地图本身是有意义的。按照@Jochen 的建议使用排序,您可以从排序列表的顶部获得 3 名员工:

    for (Map.Entry<String, List<Employee>> entry : empMap.entrySet()) {
        System.out.println(entry.getKey());  // print department name
    
        entry.getValue().stream()
                .sorted(Comparator.comparingDouble(Employee::getSalary).reversed())
                .limit(3)
                .forEach(System.out::println);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-07-02
      • 1970-01-01
      • 2018-06-08
      • 1970-01-01
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多