How to sort a hashmap in Java?
In Java, HashMap is an unordered collection that does not store key-value pairs in a specific order. If you want to sort the elements in a HashMap, you can convert it to an ordered collection, such as TreeMap.
TreeMap is an ordered map implemented based on red-black tree, which sorts the keys either according to their natural order or a custom Comparator. Here is an example of using a Comparator to sort a HashMap by keys.
import java.util.*;
public class SortHashMap {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("Tom", 30);
hashMap.put("Alice", 25);
hashMap.put("Bob", 35);
hashMap.put("John", 40);
TreeMap<String, Integer> sortedMap = new TreeMap<>(new Comparator<String>() {
public int compare(String s1, String s2) {
return s1.compareTo(s2); // 按照键的自然顺序排序
}
});
sortedMap.putAll(hashMap);
for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Output result:
Alice: 25
Bob: 35
John: 40
Tom: 30
In this example, we start by creating a HashMap and adding some key-value pairs. Then, we create a TreeMap and provide a custom Comparator that compares the keys based on their natural order. Finally, we use the putAll() method to transfer the elements from the HashMap to the TreeMap, and use entrySet() to iterate through the sorted key-value pairs.