devvapp
devvapp

Reputation: 143

Merge multiple list of different Objects with a common field into another list

I was trying to merge multiple list of objects with a common field into another list.
for example: List< ObjA>, List< ObjB>, List< ObjC>, List< ObjD>
ObjA : String id; String name, String a; String b;
ObjB : String id; String address; String x;
ObjC : String id; String phone; String y;
ObjD : String id; String zipcode;

Now I would like to merge these lists into List< ObjZ> in a very efficient way.
ObjZ: String id; String name, String a; String b; String address; String x; String phone; String y; String zipcode;

Can anyone please help me in writing an efficient code for the above?

Upvotes: 4

Views: 1954

Answers (1)

Mike
Mike

Reputation: 2425

Use a Map instead of a List, and make all the Objs implement an interface that defines getId() which you use as the key. Then for each entry in List A-D get (and possibly create ObjZ) from the Map and update its details.

You could make it quite generic. Java pseudocode:

interface ObjCopier {
  String getId();
  void copyToObjZ(ObjZ z);
}

e.g.

class ObjA implements ObjCopier {
  ...

  String getId() { return id; } 

  void copyToObjZ(ObjZ z) {
    z.setName(name);
    z.setA(a);
    ...
  }

}

And then the final bit to merge it all:

public void mergeObj(Map<String, ObjZ> map, Collection<? extends ObjCopier> list) {
  for (ObjCopier obj : list) {
    ObjZ z = getOrCreateObjZFromMap(map, obj.getId());
    obj.copyToObjZ(z);
  }
}

And call mergeObj() against all the lists you have.

If you're talking about an extremely large data set, and there is no overlap in fields across the various ObjA-ObjD, you could consider using a thread pool where each of the mergeObj() methods is run in a different thread. You'd need to synchronize getOrCreateObjZFromMap(), or pre-create all ObjZ instances before starting the threads. This could greatly speed up the process, but your mileage may vary so always best to test with data that reflects your situation.

Upvotes: 6

Related Questions