Sorting Maps
Maps are used to store key-value pairs. We can sort maps based on their keys or values. TreeMap can also be used to store key-value pairs in a sorted order.
The following code demonstrates sorting a map of integers using the sort()
method:
public static void main(String[] args) {
Map<Integer, String> map = new TreeMap<Integer, String>();
map.put(6, "Apple");
map.put(3, "Banana");
map.put(1, "Mango");
map.put(9, "Orange");
System.out.println("Map before sorting: " + map);
// Sorting by keys
Map<Integer, String> sortedByKeyMap = new TreeMap<Integer, String>(map);
System.out.println("Map after sorting by keys: " + sortedByKeyMap);
// Sorting by value
List<Map.Entry<Integer, String>> list = new ArrayList<Map.Entry<Integer, String>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, String>>() {
public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
Map<Integer, String> sortedByValueMap = new LinkedHashMap<Integer, String>();
for (Map.Entry<Integer, String> entry : list) {
sortedByValueMap.put(entry.getKey(), entry.getValue());
}
System.out.println("Map after sorting by values: " + sortedByValueMap);
}
To run this code, navigate to the ~/project
directory in the terminal and execute the following commands:
$ javac Sorting.java
$ java Sorting
This code will sort the map by its keys and values.