Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate and Map two lists in java 8

Tags:

java

I have 2 lists:

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

Given the size of list1 is the same as list2

I want to iterate ove the list2 and if the name2 of list2 is not null than update the name1 of list1.

here 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?

like image 844
youssef Liouene Avatar asked Feb 15 '16 11:02

youssef Liouene


2 Answers

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)
like image 193
sprinter Avatar answered Oct 08 '22 07:10

sprinter


As I mentioned in the comments. If the id is a uniqe identifier for your objects, then a Map is more appropriate than a List.

So you better work on such a map (assuming id is an integer):

Map<Integer, Object1> obj1map;

You could create that map from your first list with

obj1map = list1.stream().collect(toMap(Object1::getId, Function.identity()));

Now you can stream over your second list and update the map accordingly:

list2
    .stream()
    .filter(o -> o.getName() != null) // remove null names
    .filter(o -> obj1map.containsKey(o.getId())) // just to make sure
    .forEach(o -> obj1map.get(o.getId()).setName(o.getName()));
like image 23
Seelenvirtuose Avatar answered Oct 08 '22 05:10

Seelenvirtuose