Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 ?

like image 380
Pierre Henry Avatar asked Nov 27 '14 16:11

Pierre Henry


People also ask

Is Java 8 stream faster than for loop?

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.

What are the methods in streams in Java 8?

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.


1 Answers

I would probably write it like this:

List<Long> deskIds = service.getAllNodesDepthFirst().stream()                                           .flatMap(p -> p.getDesks().stream())                                           .map(Desk::getId)                                           .collect(toList()); 
like image 111
assylias Avatar answered Sep 18 '22 15:09

assylias