Last Updated : 11 Jul, 2025
The headMap() method of
NavigableMap interface in Javais used to return a view of the portion of this map whose keys are less than (or equal to, if inclusive is true) toKey.
Syntax
:
NavigableMap<K, V> headMap(K toKey,
boolean inclusive)
Where, K is the type of key maintained by this map and V is the value associated with the key in the map.
Parameters
: This function accepts two parameter:
Return Value
: It returns a view of the portion of this map whose keys are less than (or equal to, if inclusive is true) toKey.
Program 1
: When the key is integer and
second argument is missing
.
Java
// Java code to demonstrate the working of
// headMap() method
import java.io.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Declaring the NavigableMap of Integer and String
NavigableMap<Integer, String> nmmp = new TreeMap<>();
// assigning the values in the NavigableMap
// using put()
nmmp.put(2, "two");
nmmp.put(7, "seven");
nmmp.put(3, "three");
System.out.println("View of map with key less than"
+ " or equal to 7 : " + nmmp.headMap(7));
}
}
View of map with key less than or equal to 7 : {2=two, 3=three}
Program 2
: With second argument.
Java
// Java code to demonstrate the working of
// headMap() method
import java.io.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Declaring the NavigableMap of Integer and String
NavigableMap<Integer, String> nmmp = new TreeMap<>();
// assigning the values in the NavigableMap
// using put()
nmmp.put(2, "two");
nmmp.put(7, "seven");
nmmp.put(3, "three");
nmmp.put(9, "nine");
// headMap with second argument as true
System.out.println("View of map with key less than"
+ " or equal to 7 : " + nmmp.headMap(7, true));
}
}
View of map with key less than or equal to 7 : {2=two, 3=three, 7=seven}
Reference
:
https://docs.oracle.com/javase/10/docs/api/java/util/NavigableMap.html#headMap(K, boolean)RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4