VOOZH about

URL: https://www.geeksforgeeks.org/java/sortedmap-headmap-method-in-java/

⇱ SortedMap headMap() method in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

SortedMap headMap() method in Java

Last Updated : 30 Sep, 2018
The headMap() method of SortedMap interface in Java is used to return a view of the portion of this map whose keys are strictly less than toKey.
  • The map returned by this method is backed by this map, so changes in the returned map are reflected in this map, and vice-versa.
  • The map returned by this method supports all optional map operations that this map supports.
Note: The map returned by this method will throw an IllegalArgumentException if any attempt is made to insert a key outside its range. Syntax:
SortedMap<K, V> headMap(K toKey)
Where, K is the type of key maintained by this Set and V is the type of values associated with the Key. Parameters: This function accepts a single parameter toKey which represents high endpoint (exclusive) of the keys in the returned map. Return Value: It returns a view of the portion of this map whose keys are strictly less than toKey. Exception:
  • ClassCastException: If the parameter toKey is not compatible with this map's comparator (or, if the map has no comparator, if toKey does not implement Comparable).
  • NullPointerException: If the parameter toKey is null and this map does not permit null keys.
  • IllegalArgumentException: If this map itself has a restricted range, and toKey lies outside the bounds of the range
Below programs illustrate the above method: Program 1:
Output:
Last Key in the map is : {1=One, 2=Two}
Program 2:
Output:
Last Key in the map is : {Five=It, Four=Code}
Reference: https://docs.oracle.com/javase/10/docs/api/java/util/SortedMap.html#headMap(K)
Comment