Open In App

Java Program to Get Sorted Sub-Map from TreeMap

Last Updated : 01 Oct, 2021
Comments
Improve
Suggest changes
2 Likes
Like
Report

TreeMap in Java are containers that store elements in a mapped fashion that is key-value and mapped value pair. Every element has a key-value and a respective mapped value. All the key values are unique and it is necessary that no two mapped values can have the same key value. It is based on Red-Black Tree implementation in which it does not matter in which order values are inserted in TreeMap, they remain sorted according to their key, unlike HashMap.

Syntax of TreeMap:

TreeMap<Integer, String> tree_map= new TreeMap<Integer, String>();

Syntax of SubMap:

Case 1: Method will include starting key but not include ending key

tree_map.submap(starting_key, ending_key);

Case 2: To include both keys, pass true with keys

tree_map.submap(starting_key, true, ending_key, true);

Case 3: To exclude any key, pass false with key 

tree_map.submap(starting_key, false, ending_key, true);

 Methods:

  1. Brute force method
  2. Using a predefined function
  3. Using defined comparator
  4. Using user-defined comparator

Method 1: Printing Default Sorted SubMap  


Output
Elements:  {1=Alpha, 2=Gamma, 3=Beta, 4=Theta, 5=DoubleAlpha}


Method 2: Reversed sorted Map using predefined functions

Example: 


Output
Elements:  {5=DoubleAlpha, 4=Theta, 3=Beta, 2=Gamma, 1=Alpha}

Method 3: Printing Sorted Sub-Map using User Defined Comparator

The idea behind the user-defined comparator is that if the user wants to sort the map according to the user's preference. Compare the function of the comparator is used to implement our sorting logic. 

Example: 


Output
Elements:  {Alpha=GeekAmongGeek, Beta=MasterGeek, DoubleAlpha=RedDotGeek, Gamma=Geek, Theta=OnwayGeek}

Method 4: Reversed Sorted Map using User Defined Comparator 


Output
Elements : {8=Alpha, 5=Beta, 4=Theta, 3=Gamma, 1=DoubleAlpha}


 


Next Article
Practice Tags :

Similar Reads