javajava-stream

Set object properties in a list based on matching object in another list using the Stream API


I have 2 lists:

  1. List1<Object1>: Object1 (name1, id1)
  2. List2<Object2>: Object2 (name2, id2)

The size of list1 is the same as list2.

I want to iterate over list2 and if the name2 of list2 is not null, then update the name1 of list1.

Jere is the code using old Java:

  for(Object1 obj1:list1) {
    for(Object2 obj2:list2) {
      if(obj1.getId1.equals(obj2.getId2)) {
        obj1.setName1(obj2.getName2);
      }
   }
}

Which is the best way to implement this with java.util.stream?


Solution

  • Just to be clear, I think your code is intended to do the following: update the name of each item in list1 to be the name of any item in list2 that has the same ID. There doesn't seem to be anything checking if the names of items in list1 are null.

    If that's correct, then:

    list2.forEach(obj2 -> list1.stream()
         .filter(obj1 -> obj1.getId().equals(obj2.getId()))
         .forEach(obj1 -> obj1.setName(obj2.getName()));
    

    If you want to check if name is null, then add a new filter before setting the name:

        .filter(Objects::isNull)