Search code examples
javaarraylistdata-structuresmergetobjectlist

Merge two object lists in java of the same type


How do i merge two object lists in java for eg: i have 2 lists listA listB with one object each like listA[name=abc,age=56, weight=null] listB[name=Null,age=Null,weight=70]

Expected result= Output[name=abc,age=56, weight=70]


Solution

  • Sorry, read your question wrong the first time.

    Here's the process you want to follow (the question is a bit unclear so I'm assuming that whether a property is null or not is an exclusive thing - for example, if A has null weight then B MUST have a non-null weight).

    1. Loop through your lists ONCE.

    2. Within each iteration, create a new object. Then check each property of the object in List A - if it's null, then add the corresponding property from B.

    3. Add new object to list.

    4. Continue iterating

    List<Object> newList = new ArrayList<Object>();
    for (int i = 0; i < listA.size(); i++) {
        Object newObject = new Object();
        Object objectA = listA.get(i);
        if (objectA.getProperty1() == null) {
           newObject.setProperty1(listB.get(i).getProperty1());
        }
        // repeat this with your other properties
        newList.add(newObject);
    }