-
Notifications
You must be signed in to change notification settings - Fork 93
/
SortMapByValue.java
31 lines (30 loc) · 1.19 KB
/
SortMapByValue.java
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
import java.util.*;
public class SortMapByValue
{
public static void main(String[] args)
{
LinkedHashMap<String, String> capitals = new LinkedHashMap<>();
capitals.put("Nepal", "Kathmandu");
capitals.put("India", "New Delhi");
capitals.put("United States", "Washington");
capitals.put("England", "London");
capitals.put("Australia", "Canberra");
Map<String, String> result = sortMap(capitals);
for (Map.Entry<String, String> entry : result.entrySet())
{
System.out.print("Key: " + entry.getKey());
System.out.println(" Value: " + entry.getValue());
}
}
public static LinkedHashMap<String, String> sortMap(LinkedHashMap<String, String> map)
{
List<Map.Entry<String, String>> capitalList = new LinkedList<>(map.entrySet());
Collections.sort(capitalList, (o1, o2) -> o1.getValue().compareTo(o2.getValue()));
LinkedHashMap<String, String> result = new LinkedHashMap<>();
for (Map.Entry<String, String> entry : capitalList)
{
result.put(entry.getKey(), entry.getValue());
}
return result;
}
}