EN
Java - sort HashMap by keys
7
points
Short solution:
Map<String, Integer> map = new HashMap<>();
// put key / value to map
// to sort map we use tree map and default String comparator
Map<String, Integer> sortedMap = new TreeMap<>();
sortedMap.putAll(map);
sortedMap.forEach((key, value) -> {
System.out.println("Key: " + key + ", Value : " + value);
});
Another short solution:
Map<String, Integer> map = new HashMap<>();
// put key / value to map
List<String> sortedKeys = new ArrayList<>(map.keySet());
Collections.sort(sortedKeys);
// we iterate over sorted keys and get from map in sorted order
for (String key : sortedKeys) {
Integer value = map.get(key);
System.out.println("Key: " + key + ", Value : " + value);
}
1. Sort HashMap by keys using TreeMap
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Example1 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("YY", 3);
map.put("ZZ", 4);
map.put("CC", 2);
map.put("AA", 1);
System.out.println("Unsorted:");
map.forEach((key, value) -> {
System.out.println("Key: " + key + ", Value : " + value);
});
System.out.println("---------");
// to sort map we use tree map and default String comparator
Map<String, Integer> sortedMap = new TreeMap<>();
sortedMap.putAll(map);
System.out.println("Sorted:");
sortedMap.forEach((key, value) -> {
System.out.println("Key: " + key + ", Value : " + value);
});
}
}
Output:
Unsorted:
Key: YY, Value : 3
Key: ZZ, Value : 4
Key: CC, Value : 2
Key: AA, Value : 1
---------
Sorted:
Key: AA, Value : 1
Key: CC, Value : 2
Key: YY, Value : 3
Key: ZZ, Value : 4
2. Sort HashMap by keys using sorted list
import java.util.*;
public class Example2 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("YY", 3);
map.put("ZZ", 4);
map.put("CC", 2);
map.put("AA", 1);
System.out.println("Unsorted:");
map.forEach((key, value) -> {
System.out.println("Key: " + key + ", Value : " + value);
});
System.out.println("---------");
List<String> sortedKeys = new ArrayList<>(map.keySet());
Collections.sort(sortedKeys);
System.out.println("Sorted:");
// we iterate over sorted keys and get from map in sorted order
for (String key : sortedKeys) {
Integer value = map.get(key);
System.out.println("Key: " + key + ", Value : " + value);
}
}
}
Output:
Unsorted:
Key: YY, Value : 3
Key: ZZ, Value : 4
Key: CC, Value : 2
Key: AA, Value : 1
---------
Sorted:
Key: AA, Value : 1
Key: CC, Value : 2
Key: YY, Value : 3
Key: ZZ, Value : 4