Skip to content

Commit 0f5d2a7

Browse files
authored
Sort The Map Based OnValues
1 parent 7f1df0c commit 0f5d2a7

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

SortTheMapBasedOnValues

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.code;
2+
import java.awt.List;
3+
import java.util.ArrayList;
4+
import java.util.Collections;
5+
import java.util.Comparator;
6+
import java.util.HashMap;
7+
import java.util.LinkedHashMap;
8+
import java.util.LinkedList;
9+
import java.util.Map;
10+
import java.util.Map.Entry;
11+
import java.util.Scanner;
12+
public class SortMaponvalues {
13+
//sorting the map entries based on the values
14+
public static void main(String[] args) {
15+
Scanner o=new Scanner(System.in);
16+
int n=o.nextInt();
17+
int ar[]=new int[n];
18+
for(int i=0;i<n;i++) {
19+
ar[i]=o.nextInt();
20+
}
21+
HashMap<Integer, Integer>map=new LinkedHashMap<>();
22+
for(int i=0;i<n;i++) {
23+
if(!map.containsKey(ar[i])) {
24+
map.put(ar[i],1);
25+
}
26+
else {
27+
map.put(ar[i],map.get(ar[i])+1);
28+
}
29+
}
30+
System.out.println(map);
31+
LinkedList<Entry<Integer, Integer>>list=new LinkedList<>(map.entrySet());
32+
Collections.sort(list,new Comparator<Map.Entry<Integer, Integer>>() {
33+
@Override
34+
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
35+
// TODO Auto-generated method stub
36+
return o2.getValue().compareTo(o1.getValue());
37+
}
38+
});
39+
System.out.println(list);
40+
int k=o.nextInt();
41+
int arr[]=new int[k];
42+
for(int i=0;i<k;i++) {
43+
arr[i]=list.get(i).getKey();
44+
System.out.println(arr[i]);
45+
}
46+
}
47+
}

0 commit comments

Comments
 (0)