2022-12-26   ES

Thinking:

The set of`Entry<key,value>`is placed in the list, and the sort function is used to complete the sort.

``````public static void main (string [] args) {
MAP <integer, Integer> MAP = NEW TREEMAP <> ();
map.put (2,4);
map.put (5,3);
map.put (1,9);
map.put (4,2);
sort (map);
}

Private Static Void Sort (MAP <Integer, Integer> MAP) {
List <Map.entry <Integer, Integer >> List = New ArrayList <> (map.entrySet ());
// The key order is sorted by the key.
list.sort (
(MAP.ENTRY <Integer, Integer> O1, Map.entry <Integer, Integer> O2) -> ->
o2.getKey (). Compareto (o1.getkey ()));
list.Foreach (System.out :: Println);
}``````

Extension: Find the value of the most repeated times in the INT array.
Thinking: First, construct a key as an int value in the array, value for its repeated number of times (can be obtained by traversing the INT array), and then the map is used to order the value, take the value of the value, take the value of the value, take the value of the value, and take it to take the value of the value.`limit 1`can. code show as below:

``````public static void main (string [] args) {
int [] ints = {2,4,5,8,1,2,2,2,2,4,4,5,5,5,8};
// Get the mapping MAP corresponding to the number and quantity
MAP <integer, Integer> MAP = NEW TREEMAP <> ();
for (int i = 0; I <TS.Length; I ++) {
int key = ints [i];
if.containskey (key) {
int Temp = map.get (key) + 1;
map.put (key, temp);
} else {
map.put (key, 1);
}
}

// Sort the map in the upside -down order
List <Map.entry <Integer, Integer >> List = New ArrayList <> (map.entrySet ());
list.sort (
(MAP.ENTRY <Integer, Integer> O1, Map.entry <Integer, Integer> O2) -> ->
o2.getValue (). Compareto (o1.getvalue ()));
list.stream (). Map (map.entry :: getkey) .limit (1). Foreach (system.out :: println);
}``````

or

``````private static void getTopTwo(){
List<Integer> source = Arrays.asList(2,4,5,8,1,2,2,4,2,2,4,4,5,5,8);
source.stream().collect(Collectors.groupingBy(x -> x,Collectors.counting()))
.entrySet()
.stream()
.sorted((Map.Entry<Integer,Long> o1,Map.Entry<Integer,Long> o2) ->
o2.getValue().compareTo(o1.getValue()))
.map(Map.Entry::getKey)
.limit(2).forEach(System.out::println);
}
``````

source