Java

Java – TreeSet Class With Example

TreeSet and HashSet are comparable, with the exception that TreeSet arranges the components in ascending order whereas HashSet does not. While HashSet does not permit null elements, TreeSet does. This class is not synchronized like the majority of the other collection classes, however it may be synchronized explicitly like follows: Collections.synchronizedSortedSet(new TreeSet(…)); SortedSet s =

In this article, we’ll look at a TreeSet sample and discuss how it differs from other collection types.

TreeSet Example:

Two TreeSet (TreeSetString> & TreeSetInteger>) are used in this example. Although we added values to both of them at random, the ultimate result is arranged in ascending order.

import java.util.TreeSet;
public class TreeSetExample {
     public static void main(String args[]) {
         // TreeSet of String Type
         TreeSet<String> tset = new TreeSet<String>();

         // Adding elements to TreeSet<String>
         tset.add("ABC");
         tset.add("String");
         tset.add("Test");
         tset.add("Pen");
         tset.add("Ink");
         tset.add("Jack");

         //Displaying TreeSet
         System.out.println(tset);

         // TreeSet of Integer Type
         TreeSet<Integer> tset2 = new TreeSet<Integer>();

         // Adding elements to TreeSet<Integer>
         tset2.add(88);
         tset2.add(7);
         tset2.add(101);
         tset2.add(0);
         tset2.add(3);
         tset2.add(222);
         System.out.println(tset2);
    }
 }

Output: You can see both the TreeSet have been sorted in ascending order implicitly.

[ABC, Ink, Jack, Pen, String, Test]
[0, 3, 7, 88, 101, 222]

d

Related Articles

Leave a Reply

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

Back to top button