Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
java
sortedmap

What is the SortedMap.tailMap() 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.

Overview

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

The SortedMap.tailMap() method obtains the part of the map whose keys are greater than or equal to a given SortedMap key.

Syntax

SortedMap.tailMap(key)

Parameter

The SortedMap.tailMap() method takes one parameter:

  • Key: This method accepts a key of SortedMap.

Return value

The SortedMap.tailMap() method returns:

  • Map: The part of the map whose keys are greater than or equal to the given key of SortedMap.

Code

Let’s look at the code snippet below:

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 from the key=25: " + s.tailMap(25));
}
}
Using SortedMap.tailMap() method in Java

Explanation

  • In line 1, we import the required package.
  • In line 2, we make a Main class.
  • In line 4, we make a main function.
  • In line 6, we declare a SortedMap consisting of Integer type keys and String type values.
  • From lines 8-13, we insert values in the SortedMap.
  • In line 15, we display the values of the SortedMap.
  • In line 17, we will call the SortedMap.tailMap() method to obtain and display the returned map. The returned map will contain (key,value) pairs of keys equal to or greater than the key passed to the SortedMap.

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

RELATED TAGS

communitycreator
java
sortedmap

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.

Keep Exploring