【问题标题】:Find Employees with same salary using Java 8 Streams使用 Java 8 Streams 查找具有相同薪水的员工
【发布时间】:2021-12-11 07:22:35
【问题描述】:

假设我们有一个 Employee 对象列表 { id, name, Salary} 。 如何找到工资相同的员工?使用Java 8 Stream API ..

我尝试了什么:- 我想这是询问如何“基于”薪水列出员工的间接方式,在这种情况下,我们可以groupBy薪水。但这将显示所有薪水和具有该薪水的员工列表。

问题:如何在这张大地图上只列出同薪员工?

我尝试过的解决方案 ::

List<Employee> employees = new ArrayList<>();

        employees.add(new Employee(1, "John" , 1000));
        employees.add(new Employee(1, "Peter" , 2000));
        employees.add(new Employee(1, "Ben" , 3000));
        employees.add(new Employee(1, "Steve" , 2000));
        employees.add(new Employee(1, "Parker" , 1000));

Map<Integer, Set<String>> map3 =  employees.stream()
                .collect(Collectors.groupingBy
                        (Employee::getSalary, Collectors.mapping
                                (Employee::getName, Collectors.toSet())));

输出

map3 :: {2000=[Steve, Peter], 3000=[Ben], 1000=[Parker, John]}


public class Employee {

public Employee(int id, String name, int salary) {
    this.id = id;
    this.name = name;
    this.salary = salary;
}

private int id;
private String name;
private int salary;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getSalary() {
    return salary;
}

public void setSalary(int salary) {
    this.salary = salary;
}

}

【问题讨论】:

    标签: java-8 java-stream


    【解决方案1】:

    你也可以像这样使用过滤器:

    employees.stream().collect(Collectors.groupingBy(Employee::getSalary)).entrySet()
                .stream()
                .filter(entry -> entry.getValue().size() > 1)
                .map(entry -> new AbstractMap.SimpleEntry<>(entry.getKey(),
                        entry.getValue()
                     .stream().map(Employee::getName).collect(Collectors.toSet())))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    

    【讨论】:

    • +1 用于提及过滤结果集而不是进行 if 条件检查。我相应地修改了我的解决方案。这个对我来说看起来有点复杂..
    【解决方案2】:

    提出以下解决方案,它使用已编码的 groupBy,然后对大小进行条件检查。

     map3.forEach((k,v) -> {
                if(v.size()>1) {
                    System.out.println("salary :: "+ k + " is same for " + v);
                }
            });
    

    OR 使用 filter ,避免 if 条件检查 ..

      map3.entrySet()
                .stream().filter(e -> e.getValue().size()>1)
                .forEach((e) -> System.out.println( "Salary :: " + 
                            e.getKey() + " is same for " + e.getValue()));
    

    输出

    薪水 :: 2000 与 [Steve, Peter] 相同

    salary :: 1000 与 [Parker, John] 相同

    【讨论】:

      猜你喜欢
      • 2020-02-14
      • 2022-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-20
      • 1970-01-01
      • 2023-03-31
      • 2011-01-30
      相关资源
      最近更新 更多