首页 > 解决方案 > 如何通过比较两个列表从一个列表中删除元素

问题描述

我有两个列表,比如 List1 和 List2。如果 List1 中已经存在,我需要从 List2 中删除元素

为避免 ConCurrentModificationException,我尝试使用 ListIterator

employeeList1 // data present
employeeList2 // data present
ListIterator<Employee> zeroList=employeeList2.listIterator();

//remove employee if already present in list1
while(zeroList.hasNext()){
for(Employee employee : employeeList1){
                    if(zeroList.next().getID().equals(employee.getId())){
zeroList.remove();
                    }
                }
            }

我在 if 条件中得到以下异常

java.util.NoSuchElementException

List1 中可能不存在该元素,但检查条件是必要的。

标签: javalistarraylist

解决方案


您可以removeAll在要从中删除元素的集合上使用方法,并将集合作为包含要删除的元素的参数传递。

List<String> list1 = new ArrayList<>();
list1.add("a");
list1.add("b");
list1.add("c");
List<String> list2 = new ArrayList<>();
list2.add("a");
list2.add("p");
list2.add("q");
list2.removeAll(list1);
System.out.println(list2);

从 list2 中删除a,因为它存在于 list1 中并pq打印,

[p, q]

编辑:这是一个Employee类的示例代码,而你的可能是不同的,但正如你所说,你的关键是employeeId因此equalshashCode方法只需要发挥作用employeeId

static class Employee {
    private long employeeId;
    private String name;
    // whatever more variables

    public Employee(long employeeId, String name) {
        this.employeeId = employeeId;
        this.name = name;
    }

    public String toString() {
        return String.format("Employee[employeeId=%s, name=%s]", employeeId, name);
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof Employee) {
            return this.employeeId == ((Employee) o).employeeId;
        }
        return false;
    }

    @Override
    public int hashCode() {
        return new Long(employeeId).hashCode();
    }
}

public static void main(String[] args) throws Exception {
    List<Employee> list1 = new ArrayList<>();
    list1.add(new Employee(1, "a"));
    list1.add(new Employee(2, "b"));
    list1.add(new Employee(3, "c"));
    List<Employee> list2 = new ArrayList<>();
    list2.add(new Employee(1, "a"));
    list2.add(new Employee(4, "d"));
    list2.add(new Employee(5, "e"));
    list2.removeAll(list1);
    System.out.println(list2);
}

尝试使用此代码并查看它打印的内容,然后只评论两者equalshashCode方法,然后看看会发生什么。在您评论这两个方法后,list1 中存在的对象将不会被删除,因为 list 不知道两个对象何时相等。


推荐阅读