Java TreeSet add(), first() and last() Method Example

Java TreeSet Examples

This Java example shows how to create a simple TreeSet in Java with an example. This example also performs the following operations on TreeSet:
  1. Add elements to TreeSet using add() method
  2. Get the first element from TreeSet using first() method
  3. Get last element from TreeSet using last() method

Create TreeSet in Java Example

package com.javaguides.collections.treesetexamples;

import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;

public class CreateTreeSetExample {
 public static void main(String[] args) {
  // Creating a TreeSet
  SortedSet<String> fruits = new TreeSet<>();

  // Adding new elements to a TreeSet

  // Returns the first (lowest) element currently in this set.
  String first = fruits.first();
  System.out.println("First element : " + first);

  // Returns the last (highest) element currently in this set.
  String last = fruits.last();
  System.out.println("Last element : " + last);

  // Returns the comparator used to order the elements in this set, or
  // null if this set uses the natural ordering of its elements.
  Comparator<?> comparator = fruits.comparator();

  SortedSet<String> tailSet = fruits.tailSet("Orange");
  System.out.println("tailSet :" + tailSet);


First element : Apple
Last element : Pineapple
tailSet :[Orange, Pineapple]