Domanda

I have a MultiMap that has multiple similar values:

{Entertainment=[5], Food=[2, 2, 2], Products=[11], Health & Beauty=[3]}

How do I count the total of these keys so that it counts as follows?

Entertainment = 1
Food = 3
Products = 1
Health & Beauty = 1

The number inside the array is the category id, so that Food has 3 occurrences.

È stato utile?

Soluzione

Either multimap.get(key).size() or multimap.keys().count(key) should work.

Documentation

Altri suggerimenti

Assuming your map is declared as follows : MultiMap<String, Integer> map, you can do the following :

for (String key : map.keySet()) {
    int count = map.get(key).size();
}

Using asMap(), you can get the Map<String, Collection<Integer>> representation of the Multimap, from which it's easy to get the count directly without multiple lookups:

for (Map.Entry<String, Collection<Integer>> entry : multimap.asMap().entrySet()) {
    System.out.println(entry.getKey() + " = " + entry.getValue().size());
}

Note: to get the Set of keys on the Multimap, you need to call keySet(), not keys() (which indeeds repeats the key as many times as it has values).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top