Open In App

NavigableMap headMap() in Java

Last Updated : 29 Sep, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

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.




// 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));
    }
}


Output:

View of map with key less than or equal to 7 : {2=two, 3=three}

Program 2: With second argument.




// 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));
    }
}


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
Previous
Next
Share your thoughts in the comments

Similar Reads