priyas
priyas

Reputation: 415

benefit of having a treeset over a manually sorted set

In collection we could sort the set or map as per to our requirement. Treeset or TreeMap also provides the sorted collection. Is there any benefit of using treeset when we require sorted collection

Upvotes: 2

Views: 2544

Answers (4)

kriegaex
kriegaex

Reputation: 67377

The posters before me have not mentioned an important criterion: If the elements in your collection change their state often after insertion, i.e. you need to re-sort the same collection several times, maybe a TreeSet or TreeMap are not ideal because elements are only sorted during insertion, never afterwards. I.e. if you change the sorting key of an element in a TreeSet/TreeMap, it will not be re-sorted automatically. You need to remove the element from the collection before updating it and re-add it after updating it, so as to make sure it will be inserted at the right spot. You could use my UpdateableTreeSet to help you keep a TreeSet sorted.

Having said the above, you can conclude that in this case maybe an unsorted collection plus using Collections.sort() on demand might be the easier way to go. Which way is faster overall depends on your situation. I guess that UpdateableTreeSet should pretty much help you keep sorting of an existing collection limited to the places where you really change sorting keys.

Upvotes: 3

Prasad S Deshpande
Prasad S Deshpande

Reputation: 1412

TreeSet

It is always beneficial to have sorted set when ever it is require.

  • log(n) time cost for the basic operations (add, remove and contains)
  • TreeSet have few handy methods to deal with the ordered set like first(), last(), headSet(), and tailSet() etc
  • The items inside TreeSet are automatically sorted according to their natural ordering if you are not giving your own comparator.

Also please go through the TreeSet documentation. TreeSet

Upvotes: 2

Kevin Day
Kevin Day

Reputation: 16383

In addition to what others have said, TreeSet has some pretty cool capabilities, like the ability to quickly obtain a sub-set.

Outside of that, it's a question of how often you need things sorted. If you are going to create 100 sets, and only need 1 or 2 of them sorted, then the overhead of sorting during insertion is probably not worth it. But if you are going to sort the set even a single time, tree set will be the way to go.

Upvotes: 1

Bharat Sinha
Bharat Sinha

Reputation: 14363

The biggest difference is

TreeSet keeps the data sorted all the time and a set which you maintain by manually sorted may not be sorted at all times.

So TreeSet is recommended if you don't want to keep sorting the set all the time.

Upvotes: 0

Related Questions