Java Print LinkedList Example

This example shows how to print LinkedList elements in Java. This example also shows how to print LinkedList of custom class objects using the toString method.

How to print LinkedList elements in Java?

There are several ways using which you can print LinkedList object in Java as given below.

1. Using for loop or enhanced for loop

Output

2. Using Java 8 Stream

If you are using Java version 8 or later, you can use the stream to print linked list elements as given below.

Output

3. Using the Arrays class

First, convert the LinkedList object to an array using the toArray method of the LinkedList class and then print the array using the toString method of the Arrays class as given below.

Output

As you may have noticed from the output, the linked list elements are enclosed in the square brackets. If you want to remove them, you can use the replace method of the String class as given below.

Output

How to print LinkedList of custom class objects?

If the LinkedList you want to print contains objects of a custom class, then the class must implement the toString method.

The toString method should return a string representation of the object and it gets called automatically when the object is printed using the System.out.println statement.

The below example shows a custom Emp class that has overridden the toString method.

Output

This example is a part of the Java LinkedList tutorial with examples.

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

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 *