TreeSet comparator() Method in Java with Examples
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface.
The comparator() method been present inside java.util.TreeSet shares an important function of setting and returning the comparator that can be used to order the elements in a TreeSet. The method returns a Null value if the set follows the natural ordering pattern of the elements.
Syntax:
comp_set = (TreeSet)tree_set.comparator()
Parameters: The method does not take any parameters.
Return Value: The comparator set is used to order the elements of the set in a specific order. It returns a Null value if the set follows the default or natural ordering pattern.
Here we will be proposing two examples below one earlier we will be using the natural ordering of the elements later using a specific comparator to understand it better.
Example 1: Using the natural ordering of the elements
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
TreeSet<Integer> tree_set = new TreeSet<Integer>();
tree_set.add( 20 );
tree_set.add( 24 );
tree_set.add( 30 );
tree_set.add( 35 );
tree_set.add( 45 );
tree_set.add( 50 );
System.out.println( "Tree Set values are: "
+ tree_set);
Comparator comp = tree_set.comparator();
System.out.println( "Since the Comparator value is: "
+ comp);
System.out.println( "it follows natural ordering" );
}
}
|
Output:
Tree Set values are: [20, 24, 30, 35, 45, 50]
Since the Comparator value is: null
it follows natural ordering
Example 2: Using a specific comparator
Java
import java.util.Comparator;
import java.util.TreeSet;
class Helper implements Comparator<String> {
public int compare(String str1, String str2)
{
String first_Str;
String second_Str;
first_Str = str1;
second_Str = str2;
return second_Str.compareTo(first_Str);
}
}
public class GFG {
public static void main(String[] args)
{
TreeSet<String> tree_set = new TreeSet<String>();
tree_set.add( "G" );
tree_set.add( "E" );
tree_set.add( "E" );
tree_set.add( "K" );
tree_set.add( "S" );
tree_set.add( "4" );
System.out.println( "Set before using the comparator: " + tree_set);
TreeSet<String> tree_set1 = new TreeSet<String>( new Helper());
tree_set1.add( "G" );
tree_set1.add( "E" );
tree_set1.add( "E" );
tree_set1.add( "K" );
tree_set1.add( "S" );
tree_set1.add( "4" );
System.out.println( "The elements sorted in descending order:" + tree_set1);
}
}
|
Output
Set before using the comparator: [4, E, G, K, S]
The elements sorted in descending order:[S, K, G, E, 4]
Last Updated :
01 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...