Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Missing items from arraylist in java

Hi I am newbie to java and was trying my hand on collections part, I have a simple query I have two array list of say employee object

class Employee
{
    private int emp_id;
    private String name;
    private List<String> mobile_numbers;

    //.....getters and setters
}

say listA and listB have the following data

    List<Employee> listA = new ArrayList<Employee>(); 
    List<Employee> listB = new ArrayList<Employee>(); 

    listA.add(new Employee("101", "E1", listOfMobileNumbers));
    listA.add(new Employee("102", "E2", listOfMobileNumbers1));
    listA.add(new Employee("103", "E3", listOfMobileNumbers2));
    listA.add(new Employee("104", "E4", listOfMobileNumber4));
    listA.add(new Employee("105", "E5", listOfMobileNumbers5));

    listB.add(new Employee("101", "E1", listOfMobileNumbers1));
    listB.add(new Employee("102", "E2", listOfMobileNumbers2));
    listB.add(new Employee("106", "E6", listOfMobileNumber6));
    listB.add(new Employee("107", "E7", listOfMobileNumber7));
    listB.add(new Employee("108", "E8", listOfMobileNumbers8));

where listOfMobileNumbers is a List<String>

Now I want to find the additional elements from the individuals list. i.e

 List<Employee> additionalDataInListA = new ArrayList<Employee>(); 
    // this list should contain 103, 104 and 105

  List<Employee> additionalDataInListB= new ArrayList<Employee>(); 
    // this list should contain 106, 107 and 108               

How do i achieve this?

Your help is appreciated.

Edit:

I don't want to use any internal functions i want to achieve it writing some manual function kind of comparison function.

I also cant override the equals function because the in my usecase i have FieldNo which is int and Values which is a List<String>.

the occurrences of field is 'n' times and every time the Values associated with that field will different.

For example : FieldNo=18 Values=["A"];

FieldNo=18 Values=["B"]; and so on...

The employee id that I had used was for only illustration purposes where it makes sense to override equals and hash code.

like image 212
user2437809 Avatar asked Oct 16 '25 10:10

user2437809


1 Answers

You can use boolean removeAll(Collection<?> c) method.

Just note that this method modifies the List on which you invoke it. In case you to keep the original List intact then you would have to make a copy of the list first and then the method on the copy.

e.g.

List<Employee> additionalDataInListA = new ArrayList<Employee>(listA);
additionalDataInListA.removeAll(listB);
like image 178
Bhesh Gurung Avatar answered Oct 18 '25 22:10

Bhesh Gurung