TreeSet in Java

In the previous post, we have learnt about LinkedHashSet. In this post, we will learn about TreeSet in java.

TreeSet has the following features.

  • Contains unique elements like HashSet.
  • The TreeSet class implements NavigableSet interface that extends the SortedSet interface.
  • Important point to note is that it sorts the elements in ascending order.
  • It is non-synchronized.

However, it can be synchronized explicitly as given below.

SortedSet s = Collections.synchronizedSortedSet(new TreeSet(elements..));

 Example:

Let’s understand this with 2 examples i.e. with String and Integer.

Create TreeSet of String type:

Output:

TreeSet : [Apple, Banana, Date, Mango, Orange, Papaya]

Example of TreeSet with Integer:

Output:

TreeSet : [5, 15, 25, 35, 45, 55]


 

Questions/Suggestions
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

1 Response

  1. September 22, 2015

    […] the Previous post, we have learnt about TreeSet in java. In this post, we will learn HashMap in […]

Leave a Reply

Your email address will not be published. Required fields are marked *