Created
January 8, 2013 20:27
-
-
Save rob-murray/4487624 to your computer and use it in GitHub Desktop.
Find the maximum count value of list of integers in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment