Java TreeMap tailMap() Method
Example
Get the entries from "Norway" to the end, first with and then without "Norway" itself:
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
TreeMap<String, String> capitalCities = new TreeMap<String, String>();
capitalCities.put("England", "London");
capitalCities.put("Austria", "Wien");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington DC");
System.out.println(capitalCities.tailMap("Norway"));
System.out.println(capitalCities.tailMap("Norway", false));
}
}
Definition and Usage
The tailMap() method returns the part of the map where the keys are greater than or equal to the specified key. By default, the specified key itself is included. Set the second parameter to false to leave it out.
The returned map is a view of the original map (it shows the same entries, it is not a copy). If you change one of them, the other one changes too.
Tip: Use the headMap() method to get the keys before a given key.
Syntax
One of the following:
public SortedMap<K,V> tailMap(K fromKey)
public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive)
K refers to the data type of the keys in the map, and V refers to the data type of the values.
Parameter Values
| Parameter | Description |
|---|---|
| fromKey | Required. The returned map has the keys that are greater than or equal to this key. It does not have to be in the map. |
| inclusive | Optional. If false, the returned map does not have fromKey. The default is true. |
Technical Details
| Returns: | A map with the entries whose keys are greater than or equal to fromKey (only greater than, if inclusive is false). |
|---|
Related Pages
❮ TreeMap Methods