Java TreeMap headMap() Method
Example
Get the entries with keys before "Norway", first without and then with "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.headMap("Norway"));
System.out.println(capitalCities.headMap("Norway", true));
}
}
Definition and Usage
The headMap() method returns the part of the map where the keys are less than the specified key. By default, the specified key itself is not included. Set the second parameter to true to include it.
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 tailMap() method to get the keys from a given key to the end of the map.
Syntax
One of the following:
public SortedMap<K,V> headMap(K toKey)
public NavigableMap<K,V> headMap(K toKey, 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 |
|---|---|
| toKey | Required. The returned map has the keys that are less than this key. It does not have to be in the map. |
| inclusive | Optional. If true, the returned map also has toKey (if it is in the map). The default is false. |
Technical Details
| Returns: | A map with the entries whose keys are less than toKey (or equal to it, if inclusive is true). |
|---|
Related Pages
❮ TreeMap Methods