Java TreeSet first() last() Methods Tutorial

In this section, we will learn what the TreeSet first() and last() methods are and how to use them in Java.

What is Java TreeSet first() Method?

The Java TressSet first() method is used to return the first element of a TreeSet object.

Note: A TreeSet list changes the order of elements that we set for it in an ascending order by default. That means if the first element you put for a such object was for example 100 but the second element was 50, behind the scene and in the memory, the first element becomes the lowest value which here is the value 50.

So we call this method to get the first and in fact, lowest element!

Java TreeSet first() Method Syntax:

public E first()

first() Method Parameters:

The method does not take an argument.

first() Method Return Value:

The return value of this method is the first element in the target TreeSet object.

first() Method Exceptions:

This method might throw one exception and that is:

NoSuchElementException: we get this exception if the TreeSet object that this method is called with was in fact empty!

Example: using TreeSet first() method

import java.util.TreeSet; 
class Main{
    public static void main(String[] args) {
        TreeSet<Integer> ts = new TreeSet<>();
        ts.add(200);
        ts.add(2);
        ts.add(3);
        ts.add(0);
        ts.add(10);
        ts.add(30);

        System.out.println(ts.first());
    }
}

Output:

0

What is Java TreeSet last() Method?

The Java TreeSet last() method is used to get the last element in a TreeSet object.

Note: as mentioned in the first() method section, the value this method returns is not the last element that we’ve set as its argument, but the highest (or largest) element in that TreeSet object. Again, this is because a TreeSet list changes the order of elements in its body.

Java TreeSet last() Method Syntax:

public E last();

last() Method Parameters:

The method does not take an argument.

last() Method Return Value:

The return value of this method is the last element in the target TreeSet object.

last() Method Exceptions:

NoSuchElementException: we get this exception if the TreeSet object that this method is called with was in fact empty!

Example: using TreeSet last() method

import java.util.TreeSet; 
class Main{
    public static void main(String[] args) {
        TreeSet<Integer> ts = new TreeSet<>();
        ts.add(200);
        ts.add(2);
        ts.add(3);
        ts.add(0);
        ts.add(10);
        ts.add(30);

        System.out.println(ts.last());
    }
}

Output:

200

As you can see, the first element we’ve put to this list is the value 200; after calling the last() method, we got the value 200! This is because in this list, the value 200 is the biggest element it has.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies