Flattening a List of List to a List with Java 8 stream API

  • A+
Category:Languages

I have the following code which could be much simpler using Java 8 stream API:

List<List<String>> listOfListValues; public List<String> getAsFlattenedList() {         List<String> listOfValues= new ArrayList<>();         for (List<String> value: listOfListValues) {             listOfValues.add(String.valueOf(value));         }         return listOfValues;     } 

I searched for a solution on SO and found this:

listOfListValues.stream()         .flatMap(List::stream)         .collect(Collectors.toList()); 

But this doesn't do the same what I want.

 


You require only a "simple" map here:

List<List<String>> listOfListValues; public List<String> getAsFlattenedList() {     return listOfListValues.stream()             .map(String::valueOf)             .collect(toList()); } 

flatMap is rather used to transform one Stream to another, which makes sense if you need more entries or less then currently available (or just a newly mapped Stream to filter/map/etc it further down), e.g.:

  • count all the unique strings of all lists:

    listOfListValues.stream()                 .flatMap(List::stream) // we want to count all, also those from the "inner" list...                 .distinct()                 .count() 
  • truncate entries after a certain size:

    listOfListValues.stream()         .flatMap(list -> {             if (list.size() > 3) // in this case we use only some of the entries                 return Stream.concat(list.subList(0, 2).stream(), Stream.of("..."));             else                 return list.stream();         })         .collect(Collectors.toList()); 
  • flattening values of a map for several interested keys:

    Map<Key, List<Value>> map = new HashMap<>(); Stream<Value> valueStream = interestedKeys.stream()                                           .map(map::get)                                           .flatMap(List::stream); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: