Sergey Shustikov Sergey Shustikov - 26 days ago 11
Java Question

Find map value with highest number of occurrences

I have a

Map<Integer,Integer>


1 10
2 10
3 20
5 20
6 11
7 22


How do I find the maximum repeated value of the map? In this case - that is 10 & 20. Repeated count is 2 on both case.

Answer

loop over the hashmap, and count the number of repetitions.

for(Integer value:myMap.values() ){
  Integer count = 1;
  if(countMap.contains(value)){
    count = countMap.get(value);
    count++;
  }

  countMap.put(value, count);
}

then loop over the result map, and find the max(s):

Integer maxValue=0;
for (Map.Entry<Integer, Integer> entry : countMap.entrySet()){
  if(entry.getValue => maxValue){
    maxValue = entry.getValue;
    maxResultList.add(entry.Key);
  }
}
Comments