Skip to content

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

Leave a Reply

Your email address will not be published.