headMap(K toKey) method

headMap(K toKey): It returns the key-value pairs in Java whose keys are strictly less than the specified key toKey.
throws ClassCastException,  if specified key toKey is incompatible for TreeMap in Java.
NullPointerException, if toKey is null and TreeMap uses natural ordering, or its comparator does not permit null keys.
It returns null if TreeMap is empty.

SortedMap<K,V> headMap(K toKey);
import java.util.TreeMap;
class ExampleOfTreeMap
	public static void main(String arg[])
		TreeMap<Integer, String> listOfNames = new TreeMap<Integer, String>();
		listOfNames.put(3, "C");
		listOfNames.put(1, "A");
		listOfNames.put(2, "D");
		listOfNames.put(6, "B");
		listOfNames.put(8, "B");
		System.out.println("Map :"+listOfNames.headMap(3));	

Output: Map :{1=A, 2=D}

Leave a Comment

Follow us on Instagram & watch the latest videos on YouTube. Click below social icons to visit our Instagram & YouTube profiles.