Search code examples
javacollectionsjava-stream

How do I remove multiple object elements from a list from another in Java 8?


I have class Employee which have 3 fields.

And I have a list of DTO objects.

public class Employee {
   private String empId;
   private String name;
   private String group;
   private String salary;       
}


List<Employee> listEmployeesA = new ArrayList<>(List.of(
 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<>(List.of(
 new Employee("101"."Mark", "A", 20000),
 new Employee("103"."Travis", "C", 5000),
 new Employee("104"."Diana", null, 3500),
 ));

I have two list for employee class, I remove all object elements from listEmployeesA which is already in the listEmployeesB only based on only property empId, name and group but not the based on salary.

I want to do something look like below example (based on few class property):

listEmployeesA.removeAll(listEmployeesB);

Expected out below list for listEmployeesA:

Employee("102"."Tom", "B", 3000),
Employee("105"."Keith", "D", 4200),
Employee("106"."Liam", "E", 6500),
Employee("107"."Whitney", "F", 6100),
Employee("108"."Tina", null,2900)
Employee("109"."Patrick", "G", 3400)

Solution

  • You can get removeAll to work with listEmployeesA.removeAll(listEmployeesB) by adding two methods to the Employee class:

      @Override
      public boolean equals (Object other)
    
      @Override
      public int hashCode () 
    

    When you do, in equals, compare only the ID, name, and group. Also, in hashCode, build a hash code from those fields. Exclude salary from both equals and hashCode.

    If you don't know how to code a good hashCode or equals method, check your IDE for a tool that can create code for these methods.

    Overriding equals works because removeAll uses equals (Object) to compare the elements in each List. Without overriding the equals method, the equals (Object o) method inherited from Object is used, which tests to see if the references are the same.

    When you override equals method, always override hashCode method.