Skip to content

Java TreeSet Get First and Last Elements Example

This example shows how to get first and last elements from the TreeSet in Java. This example also shows how to get the lowest (smallest) or highest (biggest) elements using the first, last, pollFirst, and pollLast methods.

How to get the first and last element from TreeSet in Java?

The TreeSet class in Java provides several methods to get these elements from the set object.

How to get the first element (lowest or smallest) from the TreeSet?

There are several ways using which we can get the element as given below.

1. Using the first method

The first method of the TreeSet class returns the lowest or smallest element from the TreeSet object.

2. Using the Iterator

We can also get an iterator over the TrreeSet and get the first element as given below.

Output

3. Using the pollFirst method

The pollFirst method removes and returns the smallest or lowest TreeSet element.

Output

Important Note: The pollFirst method removes the first element from the TreeSet.

4. Using Java 8

If you are using Java version 8 or later you can use the stream to get the element from the set as given below.

Output

How to get the last element (highest or biggest) from the TreeSet?

We can use the below given methods to get the last (or biggest or highest) element from the TreeSet in Java.

1. Using the last method

The last method of the TreeSet class returns the highest or biggest element from the set.

Output

2. Using the iterator

We can also use an Iterator over TreeSet elements to get the highest element from the set.

Output

3. Using the pollLast method

The pollLast method removes and returns the highest or biggest element of the set.

Output

As we can see from the output, the pollLast method removes and returns the element from the TreeSet.

This example is a part of the Java TreeSet Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 TreeSet

About the author

Leave a Reply

Your email address will not be published.