【发布时间】: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