TreeSet Example in Java
TreeSet is a NavigableSet implementation based on a TreeMap. Sorting in the TreeSet makes it different from the HashSet. In TreeSet the elements are sorted ascending using their nartural sorting order. You can change the sorting by providing a Comparator while constructing a TreeSet.
TreeSet implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).
Null is not allowed in a TreeSet unless you specify a comparator that can handle a Null.
TreeSet Example in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | package com.kscodes.collections; import java.util.TreeSet; public class TreeSetExample { public static void main(String args[]) { // Create a TreeSet TreeSet<String> stringTreeSet = new TreeSet<>(); // Add elements to the TreeSet stringTreeSet.add("Zebra"); stringTreeSet.add("Cat"); stringTreeSet.add("Ball"); stringTreeSet.add("Tiger"); stringTreeSet.add("Elephant"); stringTreeSet.add("Apple"); // Print TreeSet System.out.println("Printing the String TreeSet"); System.out.println(stringTreeSet.toString()); System.out.println("-------------------------"); TreeSet<Integer> integerTreeSet = new TreeSet<>(); // Add elements to the TreeSet integerTreeSet.add(500); integerTreeSet.add(250); integerTreeSet.add(1000); integerTreeSet.add(1); integerTreeSet.add(4000); integerTreeSet.add(35); // Print TreeSet System.out.println("Printing the Integer TreeSet"); System.out.println(integerTreeSet.toString()); } } |
Output
The elements get sorted naturally and you can see that in the output when we print the TreeSet
1 2 3 4 5 | Printing the String TreeSet [Apple, Ball, Cat, Elephant, Tiger, Zebra] ------------------------- Printing the Integer TreeSet [1, 35, 250, 500, 1000, 4000] |