如何在Java 8中从一个列表中删除另一个列表中的多个对象元素
·
有一个名为 Employee 的类,它有 4 个字段。
@Data
public static class Employee {
private String empId;
private String name;
private String group;
private int salary;
public Employee(String empId, String name, String group, int salary) {
this.empId = empId;
this.name = name;
this.group = group;
this.salary = salary;
}
}
有两个员工类列表,仅根据empId、name 和 group属性,而不根据salary,从 listEmployeesA 中删除所有已在 listEmployeesB 中的对象元素。
public static void main(String[] args) {
List<Employee> listEmployeesA = new ArrayList<>(Arrays.asList(
new Employee("101", "Mark", "A", 20000),
new Employee("102", "Tom", "B", 3000),
new Employee("103", "Travis", "C", 5000),
new Employee("104", "Diana", null, 3500),
new Employee("105", "Keith", "D", 4200),
new Employee("106", "Liam", "E", 6500),
new Employee("107", "Whitney", "F", 6100),
new Employee("108", "Tina", null, 2900),
new Employee("109", "Patrick", "G", 3400)
));
List<Employee> listEmployeesB = new ArrayList<>(Arrays.asList(
new Employee("101", "Mark", "A", 20000),
new Employee("103", "Travis", "C", 5000),
new Employee("104", "Diana", null, 3500)
));
// 创建判断是否在 listEmployeesB 中的条件
Predicate<Employee> inListB = emp -> listEmployeesB.stream()
.anyMatch(b -> Objects.equals(emp.getEmpId(), b.getEmpId()) &&
Objects.equals(emp.getName(), b.getName()) &&
Objects.equals(emp.getGroup(), b.getGroup()));
// 过滤并收集结果
List<Employee> result = listEmployeesA.stream()
.filter(inListB.negate())
.collect(Collectors.toList());
System.out.println( result);
}
结果
更多推荐
所有评论(0)