Java Program to Sort map by keys

To understand this example, you should have the knowledge of the following Java programming topics:


Example: Sort a map by keys using TreeMap

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

class Main {
  public static void main(String[] args) {

    // create a hashmap
    Map<String, String> languages = new HashMap<>();
    languages.put("pos3", "JS");
    languages.put("pos1", "Java");
    languages.put("pos2", "Python");
    System.out.println("Map: " + languages);

    // create a tree map from the map
    TreeMap<String, String> sortedNumbers = new TreeMap<>(languages);
    System.out.println("Map with sorted Key" + sortedNumbers);

  }
}

Output

Map: {pos1=Java, pos2=Python, pos3=JS}
Map with sorted Key{pos1=Java, pos2=Python, pos3=JS}

In the above example, we have created a map named languages using HashMap. Here, the map is not sorted.

To sort the map, we created a treemap from the map. Now, the map is sorted by its keys.

Did you find this article helpful?