Open In App

Java Program to Get Sorted Sub-Map from TreeMap

Improve
Improve
Like Article
Like
Save
Share
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 keyvalue 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  

Java




// Java Program to  Get Sorted Sub-Map from TreeMap
 
// Importing all classes of
// java.util package
import java.util.*;
 
public class GFG {
   
    // Main driver code
    public static void main(String[] args)
    {
        // Create a TreeMap
        TreeMap<Integer, String> my_map
            = new TreeMap<Integer, String>();
 
        // Adding Element to TreeMap
        my_map.put(5, "DoubleAlpha");
        my_map.put(1, "Alpha");
        my_map.put(3, "Beta");
        my_map.put(2, "Gamma");
        my_map.put(4, "Theta");
 
        // Printing default sorted elements in given range
        // using subMap function
        System.out.println(
            "Elements:  "
            + my_map.subMap(1, true, 5, true));
    }
}


Output

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

Method 2: Reversed sorted Map using predefined functions

Example: 

Java




// Java Program to  Get Sorted Sub-Map from TreeMap
// using predefined functions
 
// Importing all classes of
// java.util package
import java.util.*;
 
public class GFG {
 
    // Main driver code
    public static void main(String[] args)
    {
        // Create a TreeMap
        TreeMap<Integer, String> my_map
            = new TreeMap<Integer, String>();
 
        // Adding elements to TreeMap
        my_map.put(5, "DoubleAlpha");
        my_map.put(1, "Alpha");
        my_map.put(3, "Beta");
        my_map.put(2, "Gamma");
        my_map.put(4, "Theta");
 
        // Reversing elements of map in
        // descending order
        Map<Integer, String> reversed_map
            = my_map.descendingMap();
 
        // Printing default reverse sorted elements
        // using subMap() function
        System.out.println("Elements:  " + reversed_map);
    }
}


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: 

Java




// Java Program to  Get Sorted Sub-Map from TreeMap
// using user-defined comparator
 
// Importing all classes of
// java.util package
import java.util.*;
 
// Class
public class GFG {
 
    // Main driver Code
    public static void main(String a[])
    {
 
        // Sorting TreeMap by key
        TreeMap<String, String> my_map
            = new TreeMap<String, String>(new UserComp());
 
        // Add key-value pair to TreeMap
        my_map.put("DoubleAlpha", "RedDotGeek");
        my_map.put("Alpha", "GeekAmongGeek");
        my_map.put("Beta", "MasterGeek");
        my_map.put("Gamma", "Geek");
        my_map.put("Theta", "OnwayGeek");
 
        // Display above added elements of TreeMap
        System.out.println(
            "Elements:  "
            + my_map.subMap("A", true, "Z", true));
    }
}
 
// Pre-defined comparator
class UserComp implements Comparator<String> {
 
    public int compare(String a, String b)
    {
        return a.compareTo(b);
    }
}


Output

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

Method 4: Reversed Sorted Map using User Defined Comparator 

Java




// Java Program to  Get Sorted Sub-Map from TreeMap
// using pre-defined comparator
 
// Importing all classes of
// java.util package
import java.util.*;
 
public class GFG {
 
    // Main driver method
    public static void main(String a[])
    {
        // Sorting treeMap by key
        TreeMap<Integer, String> my_map
            = new TreeMap<Integer, String>(new UserComp());
 
        // Adding key-value pair to TreeMap
        my_map.put(1, "DoubleAlpha");
        my_map.put(8, "Alpha");
        my_map.put(5, "Beta");
        my_map.put(3, "Gamma");
        my_map.put(4, "Theta");
 
        // Display elements added of TreeMap
        System.out.println("Elements : " + my_map);
    }
}
 
// Defined comparator
class UserComp implements Comparator<Integer> {
 
    public int compare(Integer a, Integer b)
    {
        if (b > a)
            return 1;
        return -1;
    }
}


Output

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

 



Last Updated : 01 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads