Java TreeMap subMap() Method
Example
Get the entries with keys between "England" and "USA":
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.subMap("England", "USA"));
System.out.println(capitalCities.subMap("England", false, "USA", true));
}
}
Definition and Usage
The subMap() method returns the part of the map where the keys are between two keys. By default, the first key is included and the last key is not. Use the version with four parameters to choose if each of the two keys is included.
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() and tailMap() methods to get the start or the end of the map.
Syntax
One of the following:
public SortedMap<K,V> subMap(K fromKey, K toKey)
public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)
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 first key of the part to return. It does not have to be in the map. |
| fromInclusive | Optional. If false, the returned map does not have fromKey. The default is true. |
| toKey | Required. The last key of the part to return. It does not have to be in the map. |
| toInclusive | Optional. If true, the returned map also has toKey. The default is false. |
Technical Details
| Returns: | A map with the entries whose keys are between fromKey and toKey. |
|---|---|
| Throws: | IllegalArgumentException - if fromKey is greater than toKey. |
Related Pages
❮ TreeMap Methods