Home > Blockchain >  Comparing Two Pojo List for changes
Comparing Two Pojo List for changes

Time:10-06

I have two Pojo Classes DriverPrimary, DriverSecondary

I am comparing Driver Primary with driver secondary and if there are any changes I need to find that out

Can you please let me know how it is done?

DriverPrimary.java

public class DriverPrimary implements Serializable {

    private static final long serialVersionUID = 1L;

    private String DriverId;
    private String role;

    
}

DriverSecondary.java

public class DriverSecondary{

    private String driverSecondaryDriverType;
    private String driverSecondaryDriverId;

}
   List<DriverPrimary> driverPrimary = new ArrayList<DriverPrimary>();
   List<DriverSecondary> driverSecondary = new ArrayList<DriverSecondary>();

driverPrimary=DataEBO.getDriverPrimary();// from datasource which is not empty and has values
driverSecondary=DataDTO.getDriverSecondary();// from datasource which is not empty and has values

SO how to compare the above two list, though the field names are different both have similar values

Edited: Removed Equals and hashcode has that will work with class with same structure. Edit2: modified the code for better understanding

CodePudding user response:

One of the lists should be remapped to the classes of another type, to make the contents of the lists "comparable":

// from datasource which is not empty and has values
List<DriverPrimary> primary = DataEBO.getDriverPrimary();
List<DriverPrimary> secondary = DataDTO.getDriverSecondary() // List<DriverSecondary>
        .stream()
        .map(sec -> new DriverPrimary(
            sec.getDriverSecondaryDriverId(),  // id  -> id
            sec.getDriverSecondaryDriverType() // type -> role
        ))
        .collect(Collectors.toList());  // List<DriverPrimary>

Then, assuming that equals and hashCode are implemented properly in DriverPrimary, the difference between the two lists may be found using for example List::removeAll (or just List::equals).

List<DriverPrimary> diff1 = new ArrayList<>(primary);
diff1.removeAll(secondary); // items in primary missing in secondary

List<DriverPrimary> diff2 = new ArrayList<>(secondary);
diff2.removeAll(primary); // items in secondary missing in primary
  • Related