English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans cet exemple, nous allons apprendre à trier le map par clé en Java.
Pour comprendre cet exemple, vous devriez comprendre ce qui suitJava programmationThème :
import java.util.HashMap; import java.util.Map; import java.util.TreeMap; class Main { public static void main(String[] args) { //Création d'une 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 key" + sortedNumbers); } }
Output result
Map: {pos1=Java, pos2=Python, pos3=JS} Map with sorted key {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.