I am having a bit of trouble reducing this for loop into a stream in Java 8, the output from the stream does not match with the for
loop
for (Object1 ob1s : getObject1s){
if (ob1s.hasChild != null){
map1.get(ob1holder).add(ob1s);
if(Objects.equals(ob1.getHolder, Boolean.TRUE))
{
map1.get(ob11holder).add(ob1s.getID);
}
if (ob1s.getObject2 != null){
for (Object2 ob2 : ob1s.getObject2.getObjects){
map.get(ob2holder).add(ob2);
}
}
}
}
Attempted:
getObject1s.stream()
.filter(ob1s -> ob1s.hasChild != null)
.map(ob1s ->
{map.get(ob1holder).add(ob1s);
if (Objects.equals(ob1.getHolder, Boolean.TRUE))
{ map.get(ob11holder).add(ob1s.getID);}
return ob1s;})
.filter(ob1s -> ob1s.getObject2 != null)
.flatMap(ob1s -> ob1s.getObject2.getObjects.stream())
.map(ob2 -> map.get(ob2holder).add(ob2));
You have no terminal operation in your stream so stream is not executed.
getObject1s.stream()
.filter(ob1s -> ob1s.hasChild != null)
.forEach(ob1s ->{
map1.get(ob1holder).add(ob1s);
if(Boolean.TRUE.equal(ob1.getHolder)){ //null safe
map1.get(ob11holder).add(ob1s.getID);
}
if (ob1s.getObject2 != null){
ob1s.getObject2.getObjects.stream()
.forEach(ob2 -> map.get(ob2holder).add(ob2));
}
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.