Objects Implementing CustomComparator
If the objects are of different types or didn’t implement the Comparable interface, we can provide a custom comparator during Treeset creation. Here is an example program.
An example of the above method is mentioned below:
Java
// Java Program to Get Two // Different Objects Into a TreeSet in Java // Using Comparable Interface import java.util.Comparator; import java.util.TreeSet; // Person Class class Person { private String name; public Person(String name) { this .name = name; } @Override public String toString() { return name; } } // Driver Class public class TreeSetExample { // main function public static void main(String[] args) { // Objects Implementing CustomComparator TreeSet<Person> treeSet = new TreeSet<>(Comparator.comparing(Person::toString)); // Adding elements in treeSet treeSet.add( new Person( "Hasan" )); treeSet.add( new Person( "Shetty" )); System.out.println( "Persons in TreeSet: " + treeSet); } } |
Persons in TreeSet: [Hasan, Shetty]
Explanation of the above Method:
In this example the class TreeSetExample showcases how to use a Treeset with a custom comparator, here comparing Person objects based on their names. The Treeset automatically orders elements , as demonstrated by adding Hasan and Shetty and printing the sorted output.
Get Two Different Objects Into a TreeSet in Java
In Java, TreeSet is a part of the Java Collection Framework and is located in the java.util package. It implements the NavigableSet interface and extends the AbstractSet and TreeSet is known for maintaining its elements in sorted order, either based on their natural order. This must be consistent with equals if it is to correctly implement the Set interface.
Methods of Getting Two Different Objects in a TreeSet in Java
In Java, if we want to store two different objects in TreeSet there are 2 ways.
- Comparable Interface
- CustomComparator