I have 2 lists:
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?
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)
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()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With