比较两个 ArrayList 的内容并将不匹配的内容存储在另一个 ArrayList 中

5

我希望比较两个ArrayList的内容。

我是这样存储对象的:

对于ArrayList 1:

Employee e1=new Employee();

e1.setID("1");
e1.setID("2");

ArrayList<Employee>list1 = new ArrayList<Employee>(); 

if(e1!=null){
    list1.add(e1);
}

对于Arraylist 2:

Employee e2=new Employee();

e2.setID("1");
e2.setID("2");
e2.setID("4");

ArrayList<Employee>list2 = new ArrayList<Employee>(); 

if(e2!=null){
    list2.add(e2);
}

现在我正在尝试以这种方式比较上述ArrayList的内容。
ArrayList<Employee>unmatchedList = new ArrayList<Employee>();   

for (Employee l1 : list1){                               
    if(!list2.contains(l1.getID())){    
        System.out.println("list2 does not contains this ID"+l1.getID());   
        Employee e3=new Employee();          
        e3.setID(l1.getID());

        if(unmatchedList==null){            
        unmatchedList=new ArrayList<Employee>();            
        unmatchedList.add(e3);          
        }

        if(unmatchedList!=null){                            
            unmatchedList.add(e3);              
        }                       
    }
}

但是我没有得到正确的未匹配列表内容,只有"4"。 我得到的未匹配列表是"1"和"2",这是错误的。 那么我该如何仅获取"unmatchedList"中的未匹配内容呢?


5
你可能想使用Set而不是ArrayList,因为Set可以轻松进行比较。但是Set不能存储重复的值。 - svz
请提供Employee类的代码。 - Subhrajyoti Majumder
2
@svz 承认,重复的员工听起来有点吓人 - 或者是双胞胎?我的雇主很想复制我们,但他从未成功过... - assylias
5个回答

5
如果你的类 Employee 被定义成这样:
public class Employee {

private int id;

public Employee(int id){
    this.id = id;
}

public int getId() {
    return id;
}

@Override
public String toString() {
    return "Id : " + this.id;
}

@Override
public boolean equals(Object obj) {
    return (obj instanceof Employee) && this.id == ((Employee)obj).getId();
}

在主方法中,您可以像这样检索不匹配的内容:
 public static void main( String[] args )
{
   List<Employee> l1 = new ArrayList<Employee>();
   l1.add(new Employee(1));
   l1.add(new Employee(2));
   l1.add(new Employee(3));
   l1.add(new Employee(4));
   l1.add(new Employee(5));


   List<Employee> l2 = new ArrayList<Employee>();
   l2.add(new Employee(4));
   l2.add(new Employee(5));


   l1.removeAll(l2);
   System.out.println(l1);

}

这将打印:[Id:1,Id:2,Id:3] 请注意,为了使此代码正常工作,您必须重写equals方法。

请注意,这实际上更改了l1的内容。在OP的问题中,元素存储在第三个列表中。我在我的答案中给出了一个简短的示例,它只是另一个构造函数调用来复制列表。 - Urs Reupke
你的解决方案对我非常有效。但是,如果我想为多个变量实现它,该如何覆盖方法呢? 例如:目前我们只有一个变量private int id; 但如果我有其他变量,如private int id1、id2、id3;那么我该如何为它们覆盖equals方法? - Java
你应该重写equals方法。equals是Object类中定义的比较对象内容的方法。提供的equals方法只是一个示例。你必须定义自己的equals方法,以便它适合你的需求。 - Dimitri
是的,我已经在Employee类中覆盖了id1的equals方法,但是如何在Employee类中为id2、id3等覆盖equals方法呢? - Java
你能具体说明一下吗?如果你想要重写equals方法,这里有一个例子:http://www.artima.com/lejava/articles/equality.html - Dimitri

1
问题出在这段代码:-
if(!list2.contains(l1.getID())){

您的list2是一个ArrayList<Employee>,并且您正在检查是否包含l1.getId()。因此,您的if条件将始终为真。


你应该在你的 Employee 类中覆盖 equalshashCode 方法,然后只需要使用:

if(!list2.contains(l1))

用于检查list2是否包含员工l1


为什么在将其添加到列表之前,您要连续三次设置id?这不会添加所有三个ID,而只会添加一个Employee,其中ID的最后一个值被设置。您需要进行更正:-
e2.setID("1");
e2.setID("2");
e2.setID("4");

list.add(e2);  // Will only add one Employee with id = 4

那么,我应该如何检查以获取通过比较两个列表得到的不匹配内容? - Java
@PravinG。还要注意,要获取不匹配的列表,您需要从两个列表中进行检查。首先检查list1的元素是否在list2中,然后反过来检查。 - Rohit Jain

1

在你的员工中添加一个equals方法,通过他们的ID进行比较,然后复制list2并调用removeAll

List<Employee> list1 = ...;
List<Employee> list2 = ...;
List<Employee> unmatchedList = new ArrayList<Employee>(list2);
unmatchedList.removeAll(list1);

完整的示例请参见@Dimitri的答案。


0

我认为你应该在你的场景中使用Set。也许这些例子可以帮到你。

Employee

package com.yourcomp;

/**
 * <br>
 * <div style="width:600px;text-align:justify;">
 *
 * TODO: Class comment.
 *
 * </div>
 * <br>
 *
 */
public class Employee {

    private int id;

    /**
     * Constructor for Employee. <tt></tt>
     */
    public Employee() {
        this(-1);
    }

    /**
     * Constructor for Employee. <tt></tt>
     */
    public Employee(int id) {
        this.id = id;
    }

    /**
     * Gets the id.
     * 
     * @return <tt> the id.</tt>
     */
    public int getId() {
        return id;
    }

    /**
     * Sets the id.
     *
     * @param id <tt> the id to set.</tt>
     */
    public void setId(int id) {
        this.id = id;
    }

    @Override
    public boolean equals(Object obj) {
        return this.id == ((Employee)obj).id;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "Employee [id=" + id + "]";
    }

    /* (non-Javadoc)
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        // TODO Auto-generated method stub
        return new Integer(id).hashCode();
    }



}

TestEmployee 类:

package com.yourcomp;

import java.util.HashSet;
import java.util.Set;

/**
 * <br>
 * <div style="width:600px;text-align:justify;">
 *
 * TODO: Class comment.
 *
 * </div>
 * <br>
 * 
 */
public class TestEmployee {

    public static void main(String[] args) {
        // creating the first set with employees having ID's 1 to 5
        Set<Employee> set1 = new HashSet<Employee>();
        for(int i=1;i<5;i++) 
            set1.add(new Employee(i));

        System.out.println(set1); // printing it

        // creating the first set with employees having ID's 3 to 8.
        // note that now you have two employees with same ID, 3 & 4
        Set<Employee> set2 = new HashSet<Employee>();
        for(int i=3;i<8;i++)
            set2.add(new Employee(i));

        System.out.println(set2);// printing the second set

        // creates a final set to contain all elements from above two sets without duplicates
        Set<Employee> finalSet = new HashSet<Employee>();
        for(Employee employee:set1)
            finalSet.add(employee); // adds first set content


        for(Employee employee:set2)
            finalSet.add(employee); // adds second set content. If any duplicates found, it will be overwritten

        System.out.println(finalSet); // prints the final set



    }
}

以及输出

[Employee [id=1], Employee [id=2], Employee [id=3], Employee [id=4]]
[Employee [id=3], Employee [id=4], Employee [id=5], Employee [id=6], Employee [id=7]]
[Employee [id=1], Employee [id=2], Employee [id=3], Employee [id=4], Employee [id=5], Employee [id=6], Employee [id=7]]

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接