Search code examples
arraylistduplicatespojo

Combining duplicate objects(POJO) within an ArrayList and generating a third and new Object Java


I have an ArrayList. It will have duplicate objects in that arraylist. The duplicate is found on a "firstId" field. There will be one another field, but that will not be used for comparing object equality. Once I find the duplicate I need to combine the info from both and populate a different object with 3 fields.

This is what I would like to do

ClassA
{
private string firstId;
private String secondId;

//equals() and hashcode() override code for firstId;
}

ClassB
{
private string firstId;
private String secondId;
private string thirdID;
}


Class A cls1A = new ClassA();
Class A cls2A = new ClassA();

ClassB clsB = new ClassB();


if(cls1A.equals(cls2A))
{
clsB.setFirstId(cls1A.getFirstId());
clsB.setSecondId(cls1A.getSecondId());
clsB.setThirdId(cls2A.getSecondID());
}

I have written quite a bit of code to identify the duplicates(basically trying to add it to a hashset and then again getting it from both the arraylist and hashset object, matching each one and trying to create the third object. But there are few bugs and also it makes my program very slow. Is there a better solution to this?


Solution

  • You really want an easy way to group objects with the same firstId value together. Two possible approaches:

    1. Sort your ArrayList (using a Comparator that looks only at firstId), then iterate over the sorted list, keeping a reference to the last item you found. If the last item and the current item match on firstId, create a new ClassB.

    2. Instead of a HashSet, use a HashMap with String key and Set values. Iterate over ArrayList, storing in it a mapping from firstId values to all the secondId values you find with that firstId.