1 PackageTest.tools;2 3 Importjava.util.Collection;4 Importjava.util.Collections;5 ImportJava.util.HashMap;6 ImportJava.util.Map;7 8 Public classTestarr {9 Ten Public Static voidMaxCount (int[] arr) { OneMap<integer, integer> map =NewHashmap<integer,integer>(); A for(inti=0; i<arr.length; i++) { - //This number is already present in the array, plus 1 - if(Map.containskey (Arr[i])) { the intCount =Map.get (Arr[i]); - /*HashMap does not allow key duplication*/ - //Map.Remove (Arr[i]); -Map.put (Arr[i], count+1); +}Else{ - //first occurrence of number, set to 1 +Map.put (Arr[i], 1); A } at } - System.err.println (map); -Collection<integer> Collection =map.values (); - //find the maximum value in map - intMaxCount =Collections.max (collection); - intnum = 0; in for(Map.entry<integer, integer>Entry:map.entrySet ()) { - //get the key that value is Maxcount, which is the most frequently occurring number in the array to if(Entry.getvalue () = =MaxCount) { +num =Entry.getkey (); - } the } *SYSTEM.OUT.PRINTLN ("Maximum number of occurrences:" +num); $SYSTEM.OUT.PRINTLN ("total occurrences" + MaxCount + "Times");Panax Notoginseng - } the + Public Static voidMain (string[] args) { A int[] arr = {1,2,3,4,1,1,1,2,2,5,4,6,7,8,3,3,5,5,5,5,1,1,1}; the MaxCount (arr); + } -}
Results:
{1=7, 2=3, 3=3, 4=2, 5=5, 6=1, 7=1, 8=1}
Maximum number of occurrences: 1
Appeared 7 times in total
The maximum number of occurrences in the array, and the interface map.entry<k,v>