Java 8: merge lists with stream API

2019-01-21 18:58发布

问题:

I have the following situation

Map<Key, ListContainer> map; 

public class ListContainer{
  List<AClass> lst;
}

I have to merge all the lists lst from the ListContainer objects from a Map map.

public static void main(String args[]){
   List<AClass> alltheObjectsAClass = map.values().stream(). // continue....    
}

Any idea how, using Java 8 stream API?

回答1:

I think flatMap() is what you're looking for.

For example:

 List<AClass> allTheObjects = map.values()
         .stream()
         .flatMap(listContainer -> listContainer.lst.stream())
         .collect(Collectors.toList());


回答2:

Alternative: Stream.concat()

Stream.concat(map.values().stream(), listContainer.lst.stream())
                             .collect(Collectors.toList()