Java: Count unique values in a Map

dictionary, java

Solution

Java 8 has been around a while now:

int count = myMap.values().stream().distinct().count();

Problem

In a `Map<K,V>` I want to know how many unique values of `V` there are. Is there something like `getValueSet()` so that I can then get the size of this set? In pseudo code: ``` Map<K,V> myMap = ...//initiate Map; Set<V> valueSet = myMap.getValueSet() int numberUniqueB = valueSet.size(); ``` Unfortunately there is no `getValueSet` method. Alternatively I can iterate through the list myself like this: ``` Set<V> mySet = new HashSet<V>(); for(Map.Entry<K,V> entry : myMap.entrySet()){ V value = entry.getValue(); mySet.add(value); } int countUniqueB = mySet.size(); ``` But this seems like I'm reinventing the wheel. Is there something in `Collections` or elsewhere that already does what I'm looking for? If not, is there a more efficient way to get the result than how I have it above?

Original source