Get Elements from LinkedList in Java Example

This example shows how to get elements from the LinkedList using the get method. The example also shows how to get elements using the peek, peekFirst, peekLast, poll, pollFirst, and pollLast methods.

How to get elements from the LinkedList in Java?

There are several ways using which you can get elements from the LinkedList in Java.

1. Using the get method

The get method of the LinkedList class returns an element of the linked list located at the specified index.

The get method returns an element at the specified index of the LinkedList object.

Output

Please remember that the index of the LinkedList starts from 0 and ends at the linked list size – 1 index. In other words, the first element of the linked list is located at index 0 and the last element is located at index list size – 1.

If the specify an index which is out of the range of the list, the get method throws IndexOutOfBoundsException exception. The index is considered out of the range it is less than 0 or it is greater than or equal to the list size.

Output

Always make sure to check the LinkedList size before accessing its elements using the get method to avoid this exception.

2. Get elements using the getFirst and getLast methods

The getFirst and getLast methods of the LinkedList class return the first and last elements of the linked list respectively.

Output

Please visit how to get first and last elements from the LinkedList example to know more.

3. Get elements using the peek, peekFirst and peekLast methods

The peek and peekFirst methods return the first element of the LinkedList while the peekLast method returns the last element of the linked list object.

Example

Output

4. Using the poll, pollFirst, and pollLast methods

The poll and pollFirst method retrieve and remove the first element of the linked list while the pollLast method retrieves and removes the last element.

Output

Important Note: The poll, pollFirst, and pollLast methods also remove the element from the LinkedList.

This example is a part of the LinkedList in Java tutorial.

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

References:
Java LinkedList Javadoc

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 *