I have Multimap, which contains two strings. Example:
1 = [key,car],
2 = [key,blue],
3 = [key,car]
Multimap definition (I am using Guava library):
ListMultimap<Integer, String> map_multi = ArrayListMultimap.create();
And this is how I put values in MultiMap:
for (int i = 0; i < list.size(); i++) {
if (i + 1 < list.size()) {
multimap.put(i,(String) list.get(i));
multimap.put(i,(String) list.get(i+1));
} else if (i + 1 == list.size()) {
}
}
I want to count the occurrences of the same value inside the multimap.
So the result should be 2 if i count how many values [key,car] are (per example I have given above) in my multimap:
[key,car] = 2[key,blue] = 1I have also tried to implement this with multi value HashMap and I was counting it with this, way (Storage is class where I store two string values inside object):
B = Collections.frequency(new ArrayList<Storage>(map.values()), map.get(number));
But I don't get the right results.
You can achieve what you want by creating a map that has your multimap values as the keys and the count as the value:
Map<Collection<String>, Long> result = map_multi.asMap().values().stream()
.collect(Collectors.groupingBy(v -> v, Collectors.counting()));
Here I've used Guava's Multimap.asMap method to get a view over the original multimap, then collected the values into a new map.
Another way, without streams:
Map<Collection<String>, Integer> result = new HashMap<>();
map_multi.asMap().values().forEach(v -> result.merge(v, 1, Integer::sum));
This uses the Map.merge method to accumulate equal values by counting its occurrences.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With