Java TreeSet - comparator() Method
The java.util.TreeSet.comparator() method returns the comparator used to order the elements in this set, or null if this set uses the natural ordering of its elements.
Syntax
public Comparator<? super E> comparator()
Here, E is the type of element maintained by the container.
Parameters
No parameter is required.
Return Value
Returns the comparator used to order the elements in this set, or null if this set uses the natural ordering of its elements.
Exception
NA.
Example:
In the example below, the java.util.TreeSet.comparator() method returns the comparator which returns null as the given set is already sorted according to the natural ordering system.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a treeset TreeSet<Integer> MySet = new TreeSet<Integer>(); //populating the set MySet.add(40); MySet.add(20); MySet.add(10); MySet.add(30); //printing the set System.out.println("MySet contains: " + MySet); //creating comparator Comparator comp = MySet.comparator(); //printing comparator value System.out.println("Comparator value is: "+ comp); } }
The output of the above code will be:
MySet contains: [10, 20, 30, 40] Comparator value is: null
❮ Java.util - TreeSet