Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Stream. Extracting distinct values of multiple maps

I am trying to extract and count the number of different elements in the values of a map. The thing is that it's not just a map, but many of them and they're to be obtained from a list of maps.

Specifically, I have a Tournament class with a List<Event> event member. An event has a Map<Localization, Set<Timeslot>> unavailableLocalizations member. I would like to count the distincts for all those timeslots values.

So far I managed to count the distincts in just one map like this:

event.getUnavailableLocalizations().values().stream().distinct().count()

But what I can't figure out is how to do that for all the maps instead of for just one.

I guess I would need some way to take each event's map's values and put all that into the stream, then the rest would be just as I did.

like image 543
dabadaba Avatar asked May 06 '16 12:05

dabadaba


People also ask

How do I get unique values in stream?

distinct() returns a stream consisting of distinct elements in a stream. distinct() is the method of Stream interface. This method uses hashCode() and equals() methods to get distinct elements. In case of ordered streams, the selection of distinct elements is stable.

Does Java stream distinct preserve order?

Java Stream distinct() MethodIf the stream is ordered, the encounter order is preserved. It means that the element occurring first will be present in the distinct elements stream. If the stream is unordered, then the resulting stream elements can be in any order.

What does flatMap return?

The flatMap() method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a map() followed by a flat() of depth 1 ( arr. map(... args).


1 Answers

Let's do it step by step:

listOfEvents.stream() //stream the events
            .map(Event::getUnavailableLocalizations) //for each event, get the map
            .map(Map::values) //get the values
            .flatMap(Collection::stream) //flatMap to merge all the values into one stream
            .distinct() //remove duplicates
            .count();   //count
like image 109
assylias Avatar answered Oct 06 '22 00:10

assylias