1

I have two ArrayLists of objects: modelList which contains Model objects, and entityList which contains Entity objects. Both Model and Entity objects have a property called id.

My goal is to loop through each Model in modelList and, if there is an Entity in entityList with the same id value, call the method merge().

Currently, I am doing this:

for (Model model : modelList) {
    for (Entity entity : entityList) {
        if (model.getId().equals(entity.getId())) merge(entity, model);
    }
}

This doesn't seem very efficient, especially with a large dataset. What would be a better way of achieving the desired result?

Thanks in advance!

Shaun Scovil
  • 3,905
  • 5
  • 39
  • 58

3 Answers3

4

Use a Map<IdType, Entity> for the Entity objects that maps the id to the Entity.

Maybe you can change the code that produces the List<Entity> to return a Map

René Link
  • 48,224
  • 13
  • 108
  • 140
0

Maybe you could build a Map models of your Model and search in it.

for(Entity entity: entityList) {
    Model model = models.get(entity.getId());
    if (model != null) {
        merge(entity, model);
    }
}

This work if you have much less model than entity!

Tyco
  • 131
  • 4
0

Based on René's answer, I went with this:

Map<String, Model> modelMap = new HashMap<String, Model>();
for (Model model : modelList)
    if (!modelMap.containsKey(model.getKey())) modelMap.put(model.getKey(), model);

Iterator it = entityList.iterator();
while (it.hasNext()) {
    Entity entity = (Entity) it.next();
    String key = entity.getKey();
    if (modelMap.containsKey(key)) merge(entity, modelMap.get(key));
    else it.remove();
}

Still open to improved answers...

Shaun Scovil
  • 3,905
  • 5
  • 39
  • 58