NavigableMap headMap() in Java
Last Updated :
29 Sep, 2018
The headMap() method of NavigableMap interface in Java is used to return a view of the portion of this map whose keys are less than (or equal to, if inclusive is true) toKey.
- The returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa.
- The returned map supports all optional map operations that this map supports.
- The returned map will throw an IllegalArgumentException on an attempt to insert a key outside its range.
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:
- toKey: This parameter refers to the key.
- inclusive: This parameter decides whether key to be deleted should be compared with equality or not.
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.
import java.io.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
NavigableMap<Integer, String> nmmp = new TreeMap<>();
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 ));
}
}
|
Output:
View of map with key less than or equal to 7 : {2=two, 3=three}
Program 2: With second argument.
import java.io.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
NavigableMap<Integer, String> nmmp = new TreeMap<>();
nmmp.put( 2 , "two" );
nmmp.put( 7 , "seven" );
nmmp.put( 3 , "three" );
nmmp.put( 9 , "nine" );
System.out.println( "View of map with key less than"
+ " or equal to 7 : " + nmmp.headMap( 7 , true ));
}
}
|
Output:
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)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...