Java 8 Streams: Make Collectors.groupingBy return Map<K, List<V>> instead of Map<K, List<List<V>>>

Viewed 3149

I have a List<SomeBean>. SomeBean contains among others, a method that returns K which may be duplicated across the list, and another method that returns List<V>. Because of how I'm using SomeBean, it's almost analogous to an entry with a key K a value List<V>.

I want to transform it into a Map<K, List<V>>, where List<V> is the concatenation of the lists with the same key K. Here is what I have done:

private static Map<K, List<V>> transformToMapOfListInTwoSteps(List<SomeBean> paginationResult) {
    Map<K, List<List<V>>> mapOfListOfList = paginationResult.stream()
            .collect(Collectors.groupingBy(SomeBean::getK, Collectors.mapping(SomeBean::getV, Collectors.toList())));

    return mapOfListOfList.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().stream().flatMap(Collection::stream).collect(Collectors.toList())));
}

However this is currently done in two steps. How can I perform the same operation without using an intermediary throwaway Map<K, List<List<V>>>?

2 Answers
Related