Java Java - 5 months ago 98
Java Question

Compare two arraylist contents and store unmatched contents in another arraylist

I want to compare two arraylist contents .

I am storing objects in them in this way.

for Arraylist 1:

Employee e1=new Employee();

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

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

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


for 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);
}


Now I am trying to compare the above arraylist contents in this way

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);
}
}
}


But I am not gettting correct unmatchedList contents as "4" only .
I am getting unmatchedList as "1" and "2" which is wrong.
So how can I get unmatched contents only in "unmatchedList"

Answer

If your class Employee is defined like this :

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();
}

in the Main method, you can retrieve the unmatch contents like this :

 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);

}

This will print : [Id : 1, Id : 2, Id : 3]

Note that for this work you must override the equals method.

Comments