A TreeSet
is a collection that is implemented as a tree data structure in Java. It extends the AbstractSet
class and implements the NavigableSet
interface. A TreeSet
stores its elements in a sorted order, and it does not allow duplicate elements.
Here is an example of how to create a TreeSet
in Java:
import java.util.TreeSet; public class Main { public static void main(String[] args) { // Create a TreeSet TreeSet<String> set = new TreeSet<>(); // Add elements to the TreeSet set.add("Apple"); set.add("Banana"); set.add("Cherry"); set.add("Date"); set.add("Elderberry"); // Print the TreeSet System.out.println(set); // Output: [Apple, Banana, Cherry, Date, Elderberry] } }Sourcewww:.lautturi.com
In this example, we create a TreeSet
of type String
and add some elements to it. The TreeSet
stores the elements in alphabetical order.
You can also create a TreeSet
with a custom comparator, which specifies the order in which the elements should be stored. Here is an example:
import java.util.Comparator; import java.util.TreeSet; public class Main { public static void main(String[] args) { // Create a comparator that sorts strings in reverse alphabetical order Comparator<String> comparator = (s1, s2) -> s2.compareTo(s1); // Create a TreeSet with the custom comparator TreeSet<String> set = new TreeSet<>(comparator); // Add elements to the TreeSet set.add("Apple"); set.add("Banana"); set.add("Cherry"); set.add("Date"); set.add("Elderberry"); // Print the TreeSet System.out.println(set); // Output: [Elderberry, Date, Cherry, Banana, Apple] } }
In this example, we create a comparator that sorts strings in reverse alphabetical order, and pass it to the TreeSet
constructor when creating the TreeSet
. The TreeSet
will use this comparator to sort the elements in the specified order.