Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count occurrences for each value in MultiMap ? (java)

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:

  • occurrences of [key,car] = 2
  • occurrences of [key,blue] = 1

I 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.

like image 918
booyah Avatar asked Mar 14 '26 17:03

booyah


1 Answers

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.

like image 126
fps Avatar answered Mar 17 '26 23:03

fps



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!