The java.util.TreeSet.comparator() method shares an important function of setting and returning the comparator that can be used to order the elements in a TreeSet. The method returns 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 method returns the comparator set 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.
Below are the programs illustrating the use of java.util.TreeSet.comparator() method:
Program 1: When using 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
Program 2: When using a specific comparator.
Set before using the comparator: [S, K, G, E, 4] The elements sorted in descendingorder: S K G E 4
- Stream sorted (Comparator comparator) method in Java
- Java | Collectors maxBy(Comparator comparator) with Examples
- Java | Collectors minBy(Comparator comparator) with Examples
- PriorityBlockingQueue comparator() method in Java
- PriorityQueue comparator() Method in Java
- TreeMap comparator() method in Java with Examples
- Comparator thenComparingLong() method in Java with examples
- Comparator comparingDouble() method in Java with examples
- Comparator naturalOrder() method in Java with examples
- ConcurrentSkipListSet comparator() method in Java with Examples
- Comparator reversed() method in Java with examples
- Comparator thenComparingDouble() method in Java with examples
- Comparator comparingLong() method in Java with examples
- SortedMap comparator() method in Java with Examples
- Comparator nullsFirst() method in Java with examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.