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

This code defines a class named “TreeSetExample” which creates an instance of the java.util.TreeSet class and performs some operations on it.

The class creates a TreeSet object set of type Integer and adds 9 integer values to it: 5, 4, 2, 7, 6, 1, 3, 9, and 8.

The code then uses a for loop to iterate over all elements in the set and outputs each element.

The code then creates a new TreeSet newSet and sets it to be a view of the portion of the original set whose elements are strictly less than 6, using the headSet method. The method headSet returns a view of the portion of the set which is less than the specified element.

The code then outputs the elements of the new set using another for loop.

In summary, this code demonstrates how to create and use a TreeSet in Java and how to obtain a view of a portion of the set using the headSet method.

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