Pierre Henry Pierre Henry - 1 month ago 6
Java Question

What is the proper way of replacing a nested for loop with streams in Java 8?

While learning Java 8 streams and lambas, I tried to replace the following nested for loops with streams :

List<Long> deskIds = new ArrayList<>();
for(ProvidedService memberService : service.getAllNodesDepthFirst()){
for(Desk d : memberService.getDesks()){
deskIds.add(d.getId());
}
}


The loop iterates a list of 'ProvidedService' objects, and for each one, iterates over a list property of 'Desk' objects, and extracts the 'Id' field to a list.

I came up with the following code using streams :

List<Long> deskIds = new ArrayList<>();
service.getAllNodesDepthFirst().stream().forEach(srv -> {
deskIds.addAll(srv.getDesks().stream().map(Desk::getId).collect(Collectors.toList()));
});


Is it the proper/optimal way to do it ? Or is there a way to do this without the second nested stream ?

Answer Source

I would probably write it like this:

List<Long> deskIds = service.getAllNodesDepthFirst().stream()
                                          .flatMap(p -> p.getDesks().stream())
                                          .map(Desk::getId)
                                          .collect(toList());