user3381995
user3381995

Reputation: 53

Get the value-set of a map while using Collectors.groupingBy()

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

Answers (1)

Tagir Valeev
Tagir Valeev

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

Related Questions