Get First or Last Element from HashSet in Java Example

This example shows how to get the first element or last element from HashSet in Java. The example also shows how to get the first or last element from HashSet using various ways.

How to get the first or last element from HashSet in Java?

The HashSet class in Java does not make any guarantees to return the elements in the same order in which they were inserted. It means that element order may not remain constant over time. It also means that the iterator of the HashSet may return elements in a different order.

So technically there is no first or last HashSet element as the order in which the elements were returned from the HashSet iterator is not constant.

However, if you want to retrieve the element that is returned first or last by the HashSet iterator, you can do so using below given ways.

How to get the first element returned by the HashSet iterator?

To get the first element from HashSet returned by the iterator, you can write below given code.

Output

As you can see from the output, the HashSet iterator returned “Five” as the first element but it was added last to the HashSet.

Using Java 8

If you are using Java version 8 or later, you can also use the below given code.

Output

I personally like the Iterator approach just because of the simplicity of it.

Using an array

Instead of using an iterator, you can also convert HashSet to an array and then access the first element of an array that is located at index 0 as given below. This approach is not recommended as it needs to allocate a new array, iterate over all elements of the HashSet and copy them to an array.

It may slow down your code and not perform well if the HashSet has a large number of elements. I am providing the code below just for the demonstration purpose.

Output

How to get the last element returned by the HashSet iterator?

Iterate over all the elements of the HashSet to get the last element as given below.

Output

While this is not recommended, we can also get the last element using the array just like we got the first as given below.

Output

Tip: If you want an ordered set, use the LinkedHashSet or TreeSet class instead of the HashSet class.

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

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

References:
Java 8 HashSet

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *

Online Shopping