Posted by & filed under Java, Programming.

Is this the easiest way to find the maximum count value of a list of integers? I have a list of integers and need to find the maximum count of how often they each occur – so loop through the list, adding to a hashmap the value and the count, then if the value already exists just increment the count.

 

public class TestApp {
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
 
        //Try with list of set values
        List<Integer> listSet = new ArrayList<Integer>();
        listSet.add(1);
        listSet.add(1);
        listSet.add(5);
        listSet.add(3);
        listSet.add(5);
        listSet.add(1);
 
        System.out.println("Maximum count value of int list with set values: ");
        System.out.println( getMaxCountValue(listSet) );
 
        //Test with list of random values
        List<Integer> listRandom = new ArrayList<Integer>();
        Random rdmGen = new Random();
        for (int i = 1; i <= 1000; i++) {
            int rdmInt = rdmGen.nextInt(25);
            System.out.println(rdmInt);
            listRandom.add(rdmInt);
        }
 
        System.out.println("Maximum count value of int list with random values: ");
        System.out.println( getMaxCountValue(listRandom) );
 
    }
 
   /**
    * Desc Method to return maximum value of occurrences of integers in list
    * @param List<Integer>
    * @returns Integer - maximum count value
    */
    private static Integer getMaxCountValue(List<Integer> myList){
 
        HashMap<Integer, Integer> frequencymap = new HashMap<Integer, Integer>();
        Integer maximum = 0;
 
        //Loop through list
        for(Integer integerObj : myList) {
            //If the hashmap contains the value then increase count
            if(frequencymap.containsKey(integerObj.intValue())) {
                frequencymap.put(integerObj.intValue(), frequencymap.get(integerObj.intValue())+1);
            }else{
                //add value with count of 1
                frequencymap.put(integerObj.intValue(), 1);
            }
        }
 
        //Loop through hashmap to find the maximum count
        for (int value : frequencymap.values()) {
            if(value > maximum){
                maximum = value;
            }    
        }
        return maximum;        
    }
 
}

 

Of course if you’re interested in the value to count relationship then could return the hashmap.

 

Leave a Reply

  • (will not be published)