A small algorithm, a small Algorithm
Write an algorithm here today
Give you a set of numbers, and then find the number that appears the most frequently and the number that appears the most.
The following code is used directly, and the main comments are described in it.
Through this algorithm, we can better understand the map set. In the code, I have written two methods to traverse the map set. Although we can master one, however, after all, it is good to learn more things, especially the second type. You should have a good understanding of it. If you don't want to talk about anything else, go directly to the code.
1 package test; 2 3 import java. util. collection; 4 import java. util. collections; 5 import java. util. hashMap; 6 import java. util. map; 7 import java. util. set; 8 9 public class Test1 {10 11 public static void main (String [] args) {12 13 // construct a map set 14 // elements in the key value storage array 15 // number of times the same element appears in the value storage array 16 Map <Integer, integer> map = new HashMap <> (); 17 int [] array = {1, 3, 4, 7, 2, 3, 5, 6}; 18 for (int I = 0; I <array. length; I ++) 19 {20 // if the same element exists, add 121 if (map) to the value. containsKey (array [I]) 22 {23 int tmp = map. get (array [I]); 24 map. put (array [1], ++ tmp); 25} 26 // otherwise, add the element directly to 27 else {28 map in the map set. put (array [I], 1); 29} 30} 31 32 Collection <Integer> count = map. values (); 33 // find the largest number in the map value, that is, the maximum number of times the number in the array appears 34 int maxCount = Collections. max (count); 35 int maxNumber = 0; 36 for (Map. entry <Integer, Integer> entry: map. entrySet () 37 {38 // obtain the key whose value is maxCount, that is, 39 if (maxCount = entry. getValue () 40 {41 maxNumber = entry. getKey (); 42} 43} 44 // Set <Integer> key = map. keySet (); 45 for (Integer key: map. keySet () 46 {47 int value = map. get (key); 48 if (value = maxCount) 49 {50 System. out. println ("the number that appears most frequently is:" + key); 51 System. out. println ("the number of occurrences is" + value); 52} 53} 54 System. out. println ("the number that appears most frequently is:" + maxNumber); 55 System. out. println ("number of occurrences:" + maxCount); 56} 57}