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.
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
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
Set before using the comparator: [4, E, G, K, S] The elements sorted in descending order:[S, K, G, E, 4]