Set<Student> ts = new TreeSet<Student>();
for(Student s : studentInfo){
ts.add(s);
}
System.out.println(ts);
I've written this above snippet in one of my case block in order to sort a collection of Student Objects.
My question is: What is the difference between using this approach and using Collections.sort();
method.
Collections sort is a method of Java Collections class used to sort a list, which implements the List interface. All the elements in the list must be mutually comparable. If a list consists of string elements, then it will be sorted in alphabetical order.
TreeSet(SortedSet): This constructor is used to build a TreeSet object containing all the elements from the given sortedset in which elements will get stored in default natural sorting order. In short, this constructor is used to convert the SortedSet object to the TreeSet object.
An ordered collection means that the elements of the collection have a specific order. The order is independent of the value. A List is an example. A sorted collection means that not only does the collection have order, but the order depends on the value of the element.
TreeSet implements the SortedSet interface. So, duplicate values are not allowed. Objects in a TreeSet are stored in a sorted and ascending order. TreeSet does not preserve the insertion order of elements but elements are sorted by keys.
The difference is that a TreeSet
keeps you data sorted at all times while the Collections.sort()
method sorts it when you call the method on your Set
.
The time complexity of Collections.sort()
is O(n*log(n))
while the TreeSet
's add()
's complexity is log(n)
. If you use the same size of data then the complexity in the TreeSet
's case will be the same because you repeat the add
operation n
times.
So you only have to decide whether you want your Set
ordered at all times or just at some point. If there is a case in your code when you don't need sorting then you don't need TreeSet
but if you will always need it to be sorted then you should use TreeSet
.
Please keep in mind that if you want to sort your Set
you have to create a List
from it first which might introduce some overhead!
Another caveat: As others mentioned TreeSet
can only take 1 Comparator
while you can supply different Comparator
s to Collections.sort()
. So it depends on your usage. You should give us more information on your use case in order to give you a thorough answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With