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>>>?