-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashMapSortByValueInDescending.java
More file actions
67 lines (45 loc) · 1.59 KB
/
HashMapSortByValueInDescending.java
File metadata and controls
67 lines (45 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.*;
public class HashMapSortByValueInDescending
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int k,l,i=1;
Map<Integer, Integer> lMap = new HashMap<Integer, Integer>();
while(n-->0)
{
k=sc.nextInt();
l=sc.nextInt();
lMap.put(k,l);
}
Set<Entry<Integer, Integer>> entrySet = lMap.entrySet();
List<Entry<Integer, Integer>> listOfentrySet = new ArrayList<Entry<Integer, Integer>>(entrySet);
Collections.sort(listOfentrySet, new SortByValue());
for(Map.Entry<Integer, Integer> entry:listOfentrySet)
System.out.print(lMap.get(entry.getKey())+" ");
}
}
class SortByValue implements Comparator<Map.Entry<Integer, Integer>>{
@Override
public int compare( Map.Entry<Integer,Integer> entry1, Map.Entry<Integer,Integer> entry2){
int second=entry2.getValue(); //just change these 2 lines to get the order as required.
int first=entry1.getValue();
if(second>first)
return 1;
if(second<first)
return -1;
else
return 0;
//return (entry2.getValue()).compareTo(entry1.getValue() );
}
}