Write a method maxOccurrences that accepts a list of integers as a parameter and returns the number of times the most frequently occurring integer (the “mode”) occurs in the list. Solve this problem using a map as auxiliary storage. If the list is empty, return 0.
package collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class MaxOccurrance {
// this method takes the list argument
public static int maxOccurrences(List<Integer> list) {
// we use hashmap to store the element as key and number of times it repeats in
// in value, and finally return key which has the max value(i.e, most times it
// repeated
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
// set the mode to 0 initilally
int mode = 0;
for (int key : list) {
if (map.containsKey(key)) {
map.put(key, map.get(key) + 1);
} else
map.put(key, 1);
// updates the mode value for every iterate
if (map.get(key) > mode)
mode = map.get(key);
}
return mode;
}
public static void main(String args[]) {
List<Integer> list = new ArrayList<Integer>();
Collections.addAll(list, 5,5, 6, 2, 8, 8, 4, 5, 2, 4, 21, 7, 0, 6, 54, 2, 5, 8, 6);
System.out.println("Number of times the most frequent occured integer is: " +maxOccurrences(list));
}
}
Output:
Number of times the most frequent occured integer is: 4