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 ?
Yes, streams are sometimes slower than loops, but they can also be equally fast; it depends on the circumstances. The point to take home is that sequential streams are no faster than loops.
With Java 8, Collection interface has two methods to generate a Stream. stream() − Returns a sequential stream considering collection as its source. parallelStream() − Returns a parallel Stream considering collection as its source.
I would probably write it like this:
List<Long> deskIds = service.getAllNodesDepthFirst().stream() .flatMap(p -> p.getDesks().stream()) .map(Desk::getId) .collect(toList());
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