listarraylistdata-structuresmergetobjectlist

Merge 2 object lists in java


i have two lists listA and listB of type object

ListA[name=abc, age=34, weight=0, height=0] data collected from excel sheet

ListB[name=null, age=0, weight=70, height=6] data collected from database

Now i want to combine both the lists into a single list

MergedList[name=abc, age=34, weight=70, height=6]

Note: my obj class has more than 15 properties so adding each property one by one using getProperty() will be time-consuming.is there a better way?


Solution

  • Convert them to a Map where the key is the name of the object ( you denoting the elements as name=abc suggests they are name/value pairs ).

    Map<String,MyMysteriousObject> converted = list.stream().collect( Collectors.toMap(MyMysteriousObject::getName, Function.identity() ) );
    

    ( replace the getName with what ever function you use to get the name of your object )

    And then just merge the maps. How to merge maps is described here for example.

    While at it, consider replacing the List with Map in your entire code. Will surely save a lot of work elsewhere too.

    But if you have to have a list again, just List<MyMysteriousObject> resultList = new ArrayList<>(resultMap);