Skip to content

Commit 43e65bd

Browse files
committed
sort hashmap using comparator
1 parent 7fcc222 commit 43e65bd

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

HashMap/sortHashmap.java

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import java.util.*;
2+
3+
class sortHashMap
4+
{
5+
public static void main(String[] args) {
6+
7+
Scanner sc=new Scanner(System.in);
8+
int n=sc.nextInt();
9+
int arr[]=new int[n];
10+
for(int i=0;i<n;i++)
11+
{
12+
arr[i]=sc.nextInt();
13+
}
14+
HashMap<Integer,Integer> map=new HashMap<>();
15+
16+
for(int i=0;i<n;i++)
17+
{
18+
map.put(arr[i],map.getOrDefault(arr[i],0)+1);
19+
}
20+
21+
for(int i : map.keySet())
22+
{
23+
System.out.println(i+"--"+map.get(i));
24+
}
25+
List<Map.Entry<Integer, Integer> > list =
26+
new LinkedList<Map.Entry<Integer, Integer>>(map.entrySet());
27+
28+
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer> >()
29+
{
30+
public int compare(Map.Entry<Integer, Integer> o1,
31+
Map.Entry<Integer, Integer> o2)
32+
{
33+
//return (o1.getValue().compareTo(o2.getValue()));
34+
return o1.getValue()-o2.getValue();
35+
}
36+
});
37+
38+
39+
40+
System.out.println(list);
41+
Collections.reverse(list);
42+
System.out.println(list);
43+
44+
List<Integer> list1 = new LinkedList<>(map.keySet());
45+
46+
Collections.sort(list1, new Comparator<Integer>()
47+
{
48+
public int compare(Integer o1,Integer o2)
49+
{
50+
//return (o1.getValue().compareTo(o2.getValue()));
51+
//for key sort
52+
return o1-o2;
53+
//if -1 then less o1 than o2 0 zero 1 greator
54+
// at time of soting values swap according to this result
55+
//for values sort
56+
//return map.get(o1)-map.get(o1);
57+
}
58+
});
59+
System.out.println(list1);
60+
HashMap<Integer,Integer> map1=new HashMap<>();
61+
62+
for(int i : list1)
63+
{
64+
map1.put(i,map.get(i));
65+
}
66+
System.out.println(map1);
67+
68+
69+
70+
71+
72+
}
73+
}

0 commit comments

Comments
 (0)