Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
java

What is the SortedMap.headMap() method in Java?

Sumit Sharma

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

In this shot, we will discuss how to use the SortedMap.headMap() method in Java, which is present in the SortedMap interface inside the java.util package.

The SortedMap.headMap() method is used to obtain the part of the map whose keys are less than a given key of SortedMap.

Parameter

The SortedMap.headMap() method takes one parameter:

  • Key: Maximum limit of key (excluded in result) to return the part of map.

Return

The SortedMap.headMap() method returns:

  • Map: Part of map whose keys are less than the key limit of the SortedMap.

Code

Let’s take a look at the code snippet.

import java.util.*;
class Main
{
public static void main(String[] args)
{
SortedMap<Integer, String> s = new TreeMap<Integer,String>();
s.put(2,"Welcome");
s.put(12,"to");
s.put(31,"the");
s.put(18,"world");
s.put(25,"of");
s.put(36,"java");
System.out.println("SortedMap mappings are: "+ s);
System.out.println("Map up till the key=25: " + s.headMap(25));
}
}
Using SortedMap.headMap() method in Java

Explanation

  • In line 1, we imported the required package.
  • In line 2, we made a Main class.
  • In line 4, we made a main function.
  • In line 6, we declared a SortedMap consisting of Integer type keys and String type values.
  • From lines 8 to 13, we inserted values in the Hashtable by using the TreeMap.put() method.
  • In line 15, we displayed the mappings of the present in the SortedMap.
  • In line 17, we used the SortedMap.headMap() method to obtain the map of keys less than key=25 of SortedMap and displayed it.

In this way, we can use the SortedMap.headMap() method in Java.

RELATED TAGS

communitycreator
java

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring