![]() |
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 JavaIn Java, if we want to store two different objects in TreeSet there are 2 ways.
Objects Implementing ComparableIf the objects are of the same type and implement the Comparable interface, they can be directly added to the Treeset. Here are some example programs. An example of the above method is mentioned below:Java
Output
Cars in TreeSet: [Ford Mustang, Honda Accord, Toyota Camry] Explanation of the above Method: In this example, the Car class implements the Comparable interface to define the neutral ordering based on the car’s brand and model. The compareTo method is overriden to provide the comparison logic. The TreeSet then automatically maintains the elements in sorted order. Objects Implementing CustomComparatorIf 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
Output
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. |
Reffered: https://www.geeksforgeeks.org
Java |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 10 |