English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In diesem Tutorial werden wir das Java SortedMap-Interface und seine Methoden lernen.
Das SortedMap-Interface der Java-Kollektionsrahmen kann die in der Abbildung gespeicherten Schlüssel sortieren.
It inheritsMap interface.
Because SortedMap is an interface, we cannot create an object from it.
To use the features of the SortedMap interface, we need to use the class TreeMap that implements it.
To use SortedMap, we must first import the java.util.SortedMap package. After importing the package, you can create a sorted map as follows.
// The SortedMap implementation is provided by the TreeMap class SortedMap<Key, Value> numbers = new TreeMap<>();
We have created a named numbers sorted mapping using the TreeMap class.
Here,
Key - Used as a unique identifier to associate each element (value) in the mapping
Value - The elements associated with the key in the map
Here, we have not used any parameters to create a sorted mapping. Therefore, the mapping will be naturally sorted (ascending).
The SortedMap interface includes all the methods of the Map interface. This is because Map is the superinterface of SortedMap.
In addition to all these methods, there are also methods specific to the SortedMap interface.
comparator() - Returns a comparator that can be used to sort the keys in the mapping
firstKey() - Returns the first key of the sorted mapping
lastKey() - Returns the last key of the sorted mapping
headMap(key) - Returns all entries of the mapping whose keys are less than the specified key key
tailMap(key) - Returns all entries of the mapping whose keys are greater than or equal to the specified key key
subMap(key1,key2) -Returns the key located at key1and key2between (including key1All entries of the mapping
import java.util.SortedMap; import java.util.TreeMap; class Main { public static void main(String[] args) { //Using TreeMap to create SortedMap SortedMap<String, Integer> numbers = new TreeMap<>(); //Insert mapping element numbers.put("Two", 2); numbers.put("One", 1); System.out.println("SortedMap: ", + numbers); //Access the first key of the map System.out.println("First key: ", + numbers.firstKey()); //Access the last key of the map System.out.println("Last key: ", + numbers.lastKey()); //Remove elements from the map int value = numbers.remove("One"); System.out.println("Delete value: ", + value); } }
Output result
SortedMap: {One=1, Two=2} First key: One Last key: Two Delete value: 1
For more information on TreeMap, please visitJava TreeMap.
Since we understand the SortedMap interface, we will use the TreeMap class to learn its implementation.