Create TreeSet in Java - How to add Elements to TreeSet

Published April 04, 2022

Creating a Java TreeSet first requires importing the java.util.TreeSet package therefore, you should import it first. Once this package has been imported, use the Syntax below to create your TreeSet:

TreeSet<Integer> TreeSet = new TreeSet<>();


The TreeSet is sorted in ascending order by default, but this can be customized using the Comparator interface.

The Common TreeSet Methods

  • add(): the specified element is inserted into the set

  • addAll(): Adds all elements of a collection to a set

  • removeAll(): removes  all elements from the set

  • remove(): removes specified element

  • first(): gets the first element of the set

  • last(): gets the last element of the set


Example of TreeSets

In this example, we create a TreeSets object and add elements with the add() and addAll() methods.

import java.util.TreeSet;

public class TreeSetExample {

    public static void main(String[] args) {

        TreeSet<Integer> TS = new TreeSet<>();

        //add elements using the add() method




        System.out.println("First TreeSet: " + TS);

        TreeSet<Integer> numbers = new TreeSet<>();


        // add element using the addAll() method


        System.out.println("Second TreeSet: " + numbers);






First TreeSet: [7, 8, 9]

Second TreeSet: [6, 7, 8, 9]

Article Contributed By :