Skip to content
Advertisement

Combining / merging object members in a list

I got a list of objects from class A in a list. Some of these objects are equal in id and name but not in list <B> , and list b is ALWAYS different.

I need to merge these so that my list is only made out of object a’s with same name and id exists and all the b from same group are collected I can make use of jdk 8 plus utils so streams are ok to use here.. Although I think reflection here is more usable?

PS: I can not change content of a of b class as they are generated classes and no access / expansion possibility

JavaScript

Advertisement

Answer

You could use

JavaScript

This constructs new lists with new A objects, which is suitable for immutable objects. Your use of List.of(…) suggests a preference towards immutable objects. If you have mutable objects and want to perform the operation in-place, you could do

JavaScript

This removes the duplicates from the list and adds their Bs to the previously encountered original. It does the minimum of changes required to get the intended list, e.g. if there are no duplicates, it does nothing.

If A objects with the same id always have the same name, in other words, there is no need for a key object checking both, you could simplify this approach to

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement