1

I want to collect a list result from a parallel stream into one list. Lets look at this code to explain my issue better. This is what I get:

List<Object> a = new ArrayList<>();

List<List<Object>> result a.parallelStream() // I get a List of List
   .map(a -> { return new ArrayList(); })
   .collect(Collectors.toList());

But what I really want to have is more like this:

List<Object> a = new ArrayList<>();

List<Object> result a.parallelStream()   // I want to add all list elements into one List of objects
   .map(a -> { return new ArrayList(); })
   .collect(Collectors.???); 
KIC
  • 5,887
  • 7
  • 58
  • 98

1 Answers1

5

flatMap can collapse the elements of the internal lists to a single list :

List<List<Object>> a = ...
List<Object> result = a.stream()
                       .flatMap (l -> l.stream())
                       .collect(Collectors.toList());
Eran
  • 387,369
  • 54
  • 702
  • 768
  • 3
    I can’t resist: [`l -> l.stream()` could simply be `List::stream`](http://stackoverflow.com/questions/25147094/turn-a-list-of-lists-into-a-list-using-lambdas#comment39146485_25147125) – Holger Feb 05 '15 at 14:38