Skip to content

Get First or Last Element from LinkedHashSet in Java Example

This example shows how to get the first or last element from LinkedHashSet in Java. This example also shows how to get the first element or the last element using an iterator, array, and Java 8 stream.

Even though the LinkedHashSet class maintains a doubly-linked list running through its elements, it does not expose any methods using which we can get LinkedHashSet elements using the index.

How to get the first element from the LinkedHashSet in Java?

1. Using an Iterator

We can get an iterator over the LinkedHashSet elements using the iterator method. Once we get an iterator, we can iterate through the elements of the LinkedHashSet and get the first element as given below.

Output

2. Using Java 8 stream

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

Output

3. By converting it to an array or List

We can convert the LinkedHashSet to an array or a List (like ArrayList or LinkedList) object and then can access the first element using the index 0.

Output

Note: This approach needs the LinkedHashSet to first converted to an array or a List object which is unnecessary just to access the element. If the LinkedHashSet contains a very large number of elements, it may slow down the code and impact the performance. Using this approach is generally not recommended.

How to get the last element from the LinkedHashSet in Java?

1. Using an Iterator

We can get the last element from LinkedHashSet in the same we got the first element given above.

Output

2. By converting it to an array or List

We can also convert LinkedHashSet to an array or a List object and then access the last element using the index as given below.

Output

This approach creates a new array from the LinkedHashSet elements and it is a costly operation in terms of performance. It may not perform well especially if the LinkedHashSet has a very large number of elements.

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

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

References:
Java 8 LinkedHashSet

About the author

Leave a Reply

Your email address will not be published.