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