Why is it better to create a TreeSet from a HashSet instead of creating a new TreeSet and adding elements to it? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why is it better to create a TreeSet from a HashSet instead of creating a new TreeSet and adding elements to it?

Hello, I was reading about Collections in Java and I found this information: "It is generally faster to add elements to the HashSet and then convert the collection to a TreeSet for a duplicate-free sorted traversal." I know that the time complexity for inserting, removing, etc. in HashSet is O (1) and in TreeSet is O (logn) for the same operations, but don't we pay for the TreeSet insertion anyway when creating the tree?

23rd Feb 2018, 1:51 PM
Roxana
Roxana - avatar
1 Answer
+ 1
Hi, That is an interesting question. Yes, you pay a price for using a TreeSet over a HashSet, but this overhead is well justified when there is a natural ordering in place. Here's my code for your reference. https://code.sololearn.com/c4hhhyD5ji7c/?ref=app Hope that helps. Chris
12th Dec 2020, 11:43 AM
Chris Ng
Chris Ng - avatar