EN
Java - sort HashMap by keys
7 points
Short solution:
xxxxxxxxxx
1
Map<String, Integer> map = new HashMap<>();
2
// put key / value to map
3
4
// to sort map we use tree map and default String comparator
5
Map<String, Integer> sortedMap = new TreeMap<>();
6
sortedMap.putAll(map);
7
8
sortedMap.forEach((key, value) -> {
9
System.out.println("Key: " + key + ", Value : " + value);
10
});
Another short solution:
xxxxxxxxxx
1
Map<String, Integer> map = new HashMap<>();
2
// put key / value to map
3
4
List<String> sortedKeys = new ArrayList<>(map.keySet());
5
Collections.sort(sortedKeys);
6
7
// we iterate over sorted keys and get from map in sorted order
8
for (String key : sortedKeys) {
9
Integer value = map.get(key);
10
System.out.println("Key: " + key + ", Value : " + value);
11
}
xxxxxxxxxx
1
import java.util.HashMap;
2
import java.util.Map;
3
import java.util.TreeMap;
4
5
public class Example1 {
6
7
public static void main(String[] args) {
8
9
Map<String, Integer> map = new HashMap<>();
10
map.put("YY", 3);
11
map.put("ZZ", 4);
12
map.put("CC", 2);
13
map.put("AA", 1);
14
15
System.out.println("Unsorted:");
16
map.forEach((key, value) -> {
17
System.out.println("Key: " + key + ", Value : " + value);
18
});
19
20
System.out.println("---------");
21
22
// to sort map we use tree map and default String comparator
23
Map<String, Integer> sortedMap = new TreeMap<>();
24
sortedMap.putAll(map);
25
26
System.out.println("Sorted:");
27
sortedMap.forEach((key, value) -> {
28
System.out.println("Key: " + key + ", Value : " + value);
29
});
30
}
31
}
Output:
xxxxxxxxxx
1
Unsorted:
2
Key: YY, Value : 3
3
Key: ZZ, Value : 4
4
Key: CC, Value : 2
5
Key: AA, Value : 1
6
---------
7
Sorted:
8
Key: AA, Value : 1
9
Key: CC, Value : 2
10
Key: YY, Value : 3
11
Key: ZZ, Value : 4
xxxxxxxxxx
1
import java.util.*;
2
3
public class Example2 {
4
5
public static void main(String[] args) {
6
7
Map<String, Integer> map = new HashMap<>();
8
map.put("YY", 3);
9
map.put("ZZ", 4);
10
map.put("CC", 2);
11
map.put("AA", 1);
12
13
System.out.println("Unsorted:");
14
map.forEach((key, value) -> {
15
System.out.println("Key: " + key + ", Value : " + value);
16
});
17
18
System.out.println("---------");
19
20
List<String> sortedKeys = new ArrayList<>(map.keySet());
21
Collections.sort(sortedKeys);
22
23
System.out.println("Sorted:");
24
// we iterate over sorted keys and get from map in sorted order
25
for (String key : sortedKeys) {
26
Integer value = map.get(key);
27
System.out.println("Key: " + key + ", Value : " + value);
28
}
29
}
30
}
Output:
xxxxxxxxxx
1
Unsorted:
2
Key: YY, Value : 3
3
Key: ZZ, Value : 4
4
Key: CC, Value : 2
5
Key: AA, Value : 1
6
---------
7
Sorted:
8
Key: AA, Value : 1
9
Key: CC, Value : 2
10
Key: YY, Value : 3
11
Key: ZZ, Value : 4