Hello everyone. In this session
let us look at the TreeSet.
TreeSet is an important implementation
of SortedSet interface.
It is a sorted type of set, very
similar to HashSet but the difference
is, it is an ordered collection and elements
are sorted in the ascending order by default.
So, inside a TreeSet, when we add
the elements, those are automatically
sorted in the ascending order.
So, let's create an object of TreeSet.
Let us use the set interface to create the object,
say set1 = new TreeSet.
Import the TreeSet and import the set interface.
Now, to create the object of a set,
you can use the var keyword if you're
using Java 10 or you can use the particular
reference type like TreeSet or you can use the set
interface because it is the parent interface.
So, you can choose any of the ways.
Now, let us add some elements to the set.
Let us say I want to add some names.
So, we have added four items, Rob,
Bob, Andy, and Charls.
And let us simply display the set over here.
So, in this case we will see four elements
in the list, but those will be sorted
automatically in the ascending order.
So, when we look at the output,
the set is automatically sorted.
So, A, B, C, and R.
Let's add some other elements.
Let's create another set , say set2 =
to new TreeSet( ); integer.
and let's quickly add some integer values.
So, we have added some random
integer values and let us also
display the set2.
So, in this case we can expect the set2
also get sorted in the ascending
order by default.
So, that is the main difference in between
the HashSet and TreeSet.
In case of HashSet, it is not an ordered
collection, in case of TreeSet,
it is an ordered collection, but it is ordered
in the sorted fashion.
It sorts the elements automatically
in the ascending order. Other than that,
all methods are same,
add, remove, clear, contents, very same to
what we have seen in the HashSet,
and union and intersection methods are similar,
converting to list is also similar.
Okay, so this is about the HashSet,
LinkedHashSet, and TreeSet in Java, and there's
also an interview question. Thank you.