Java Program to Get Sorted Sub-Map from TreeMap
Last Updated :
01 Oct, 2021
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:
- Brute force method
- Using a predefined function
- Using defined comparator
- 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));
}
}
OutputElements: {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);
}
}
OutputElements: {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);
}
}
OutputElements: {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;
}
}
OutputElements : {8=Alpha, 5=Beta, 4=Theta, 3=Gamma, 1=DoubleAlpha}
Similar Reads
Getting Synchronized Map from Java TreeMap
TreeMap is a part of the Java Collections framework. Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class. It provides an efficient means of storing key-value pairs in sorted order. Java TreeMap contains only unique elements. It cannot
2 min read
Java Program to Check if the TreeMap is Empty
The TreeMap in Java is used to implement Map interface and NavigableMap along with the AbstractMap Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. Approaches: Using the isEmpty() methodU
3 min read
Java Program to Implement TreeMap API
The TreeMap is used to implement Map interface and NavigableMap along with the AbstractMap class in java. The map is sorted by the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. Now, in implementing TreeMap API, the task is div
6 min read
Program to convert a Map to a Stream in Java
A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Below are various method to convert Map to Stream in Java: Converting complete Map<Key, Value> into Stream: This can be done with the help of Map.entrySet() method which return
4 min read
Program to Convert HashMap to TreeMap in Java
HashMap is a part of Javaâs collection since Java 1.2. It provides the basic implementation of Map interface of Java which stores the data in (Key, Value) pairs. To access a value in HashMap, one must know its key. HashMap is known as HashMap because it uses a technique Hashing for storage of data.
6 min read
Java Program for Heap Sort
Heap sort is a comparison-based sorting technique based on the Binary Heap data structure. It is similar to the selection sort where first find the maximum element and place it at the end. We repeat the same process for the remaining element. Heap Sort in JavaBelow is the implementation of Heap Sort
3 min read
Getting submap, headmap, and tailmap from Java TreeMap
The TreeMap is used to implement Map interface and Navigable Map with the AbstractMap class in Java. Various constructors can be used in the TreeMap by to maintain the sorted ordering of its keys. A. subMap() method of TreeMap The subMap() method in Java is used to return the part or portion of the
8 min read
Java Program to Sort LinkedHashMap By Values
The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion, but it never maintained the track and order of insertion which the LinkedHashMap provides where the element
3 min read
Java Program to Find the Index of the TreeSet Element
Unlike the List classes like ArrayList or a LinkedList, the TreeSet class does not allow accessing elements using the index. There are no direct methods to access the TreeSet elements using the index and thus finding an index of an element is not straightforward. Methods: There are primarily three s
6 min read
How to Merge Two TreeMaps in Java?
In Java, TreeMap is a pre-defined class that implements the NavigableMap interface and extends the AbstractMap class. In this article, we will learn to Merge Two Tree Maps in Java. Program to Merge Two TreeMaps in JavaWe are using the putAll method is inherited from the AbstractMap class in this man
2 min read