English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In diesem Beispiel werden wir lernen, wie man eine Map in Java nach Schlüsseln sortiert.
Um diesen Beispiel zu verstehen, sollten Sie die folgenden Kenntnisse habenJava-ProgrammierungThema:
import java.util.HashMap; import java.util.Map; import java.util.TreeMap; class Main { public static void main(String[] args) { //Erstellen Sie eine 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.