Difference between Collections.sort () and getting a sorted collection by adding to TreeSet?

Set<Student> ts = new TreeSet<Student>(); for(Student s : studentInfo){ ts.add(s); } System.out.println(ts); 

I wrote this snippet above in one of the case blocks to sort the Student Objects collection. My question is: what is the difference between using this approach and using the Collections.sort(); method Collections.sort(); .

+9
java collections algorithm data-structures
Sep 12 '13 at 9:42 on
source share
2 answers

The difference is that a TreeSet allows TreeSet to sort data at all times, and the Collections.sort() method sorts it when you call the method on Set .

The time complexity of Collections.sort() is O(n*log(n)) , and the complexity of TreeSet add() is log(n) . If you use the same data size, the complexity in the case of TreeSet will be the same as you repeat the add n operation.

Thus, you only need to decide whether you want your Set be ordered at all times or only at some point. If there is a case in your code where you do not need sorting, you do not need a TreeSet , but if you always need to sort it, you should use a TreeSet .

Remember that if you want to sort a Set , you need to create a List first, which can lead to some overhead!

Another disclaimer:. As mentioned above, a TreeSet can only accept 1 Comparator , while you can provide different Comparator - Collections.sort() . So it depends on your use . You should provide us with more information about your use case in order to give you a comprehensive answer.

+11
Sep 12 '13 at 9:45 on
source share

1) TreeSet , like all Set , rejects duplicate values.

2) TreeSet supports sorting every time you insert elements, and a list sorted using Collections.sort () will only be sorted after calling sort () (and will not support this view when adding ()).

3) Collections.sort () allows you to sort the list according to different criteria using different Comparators . With a TreeSet, you can also give a Comparator, but you need to instantiate one TreeSet for each comparator.

+4
Sep 12 '13 at 9:48 on
source share



All Articles