TreeSet basics

With TreeSets, unlike HashSets, the elements are already arranged in a specific order.

Syntax

import java.util.TreeSet;

TreeSet<String> hashSet = new TreeSet<String>();

TreeSet Example

import java.util.TreeSet;

class TreeSetExample {
    public static void main(String[] args) {
        TreeSet<Integer> set = new TreeSet<Integer>();
                        
        set.add(5);
        set.add(4);
        set.add(2);
        set.add(7);
        set.add(6);
        set.add(1);
        set.add(3);
        set.add(9);
        set.add(8);

        // output elements using enhanced for loop
        for (Integer s : set) {
            System.out.println(s);
        }

        TreeSet<Integer> newSet;
        // Returns a view of the portion of this set whose elements are strictly less than toElement.
        newSet = (TreeSet<Integer>)set.headSet(6);

        System.out.println("Head set");
        for (Integer s : newSet) {
            System.out.println(s);
        }
    }
}
Output
1
2
3
4
5
6
7
8
9
Head set
1
2
3
4
5