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

        TS.add(7);

        TS.add(8);

        TS.add(9);

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

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

        numbers.add(6);

        // add element using the addAll() method

        numbers.addAll(TS);

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

    }

}

 

 

Output:

First TreeSet: [7, 8, 9]

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


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

54 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions