English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)

Java Reader/Writer

Other Java Topics

Java Program Sorts Map by Key

Comprehensive Java Examples

In this example, we will learn how to sort the map by keys in Java.

To understand this example, you should know the followingJava ProgrammingTopic:

Example: Use TreeMap to sort the map by key

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 TreeMap from map
    TreeMap<String, String> sortedNumbers = new TreeMap<>(languages);
    System.out.println("Map with sorted keys" + sortedNumbers);
  }
}

Output Result

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

In the above example, we used HashMap to create a map named planguages. 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.

Comprehensive Java Examples