Reputation: 53
I have a Collection<A>
that i want to group by its type. I can get the type of A via a getType
method. The result should be of the type Collection<Collection<A>>
. Eg:
Input: [A1 ,A2, A3, A1, A3, A4]
(A1 is an object of type '1', so on)
Output: [[A1, A1], [A2], [A3, A3], [A4]]
Here's is what I've written:
listOfAs.stream().collect(Collectors.groupingBy(SomeClass::getType)).values();
Is there a way I can directly obtain the value-set of the map generated, instead of generating the map and then extracting the value-set from it using the values()
?
Upvotes: 2
Views: 645
Reputation: 100309
Well internally you will still need to generate such map. It's possible to create a custom collector though:
public static <T, K>
Collector<T, ?, Collection<List<T>>> groups(Function<? super T, ? extends K> classifier) {
return Collectors.collectingAndThen(Collectors.groupingBy(classifier), Map::values);
}
So you can use it like this:
Collection<List<SomeClass>> result = listOfAs.stream().collect(groups(SomeClass::getType));
Note that internally it doesn't differ much from your solution. You just incorporate the values()
call inside the collector.
Upvotes: 3