Site icon JavaGoal

headMap(K toKey, boolean inclusive) method

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

Syntax:  SortedMap<K,V> headMap(K toKey, boolean inclusive); 
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, false));
		System.out.println("Map :"+listOfNames.headMap(3, true));
	}
}

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

Exit mobile version