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

What is the SortedMap.subMap() method in Java? Answer

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

The SortedMap.subMap() method is used to obtain the part of the map for a given range of keys of SortedMap.

Parameters

The SortedMap.subMap() method takes two parameters:

  • Key1: Minimum limit of key (included in result) to return the part of map.
  • Key2: Maximum limit of key (excluded in result) to return the part of map.

Return value

The SortedMap.subMap() method returns:

  • Map: Part of map for the range of keys in the SortedMap.

Code

Let’s look at the below 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 from the min_limit_key=18 to max_limit_key=36: " + s.subMap(18,36));


}
}

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.subMap() method to obtain the subMap for a range of keys and displayed it.

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

What is the SortedMap.subMap() method in Java? Review:

In our experience, we suggest you solve this What is the SortedMap.subMap() method in Java? and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the What is the SortedMap.subMap() method in Java?

Find on Educative

Conclusion:

I hope this What is the SortedMap.subMap() method in Java? would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published.