Print LinkedList in java

Print LinkedList in java

Java inbuilt LinkedList

Java inbuilt LinkedList class uses doubly linked list as internal data structure to store its elements. It is subclass of AbstractList and implements List and Deque interfaces.

Insertion and deletion of elements is faster than ArrayList as it interally uses double LinkedList.

Print LinkedList using a for loop

The most common method of printing out elements in a List is by using a for-loop. Since LinkedList is an implementation of a List, we can use a for loop to get elements that are stored in each index of the LinkedList.

Just as with other Lists, a Linked List starts from index 0, and we can use the size() method to get the total number of elements in the List.

For each iteration of the for loop, pass the index to the get(index) method, which will return the element in the specific address.


0 = cow
1 = hen
2 = goat
3 = sheep
4 = donkey

Print LinkedList using Enhanced for loop

An enhanced for loop is an alternative to a for-loop. It makes the code readable as it is short and descriptive. It also reduces the chances of getting a bug in your code by eliminating errors such as IndexOutofBoundException, which is prone to occur in a for-loop.

Most developers consider using an enhanced for loop as a best practice due to the above-mentioned advantages. Enhanced for-loop cannot traverse elements backwards because it does not support index operations compared to a for-loop.

An enhanced for loop can be used to iterate through a LinkedList to print out the elements in the List. The type of variable of the enhanced for loop will be similar to that being passed to the LinkedList.



Print LinkedList using streams

The Java stream was introduced in Java 8 and made use of functional programming to operate on a collection of elements.

Streams use aggregate operations with several intermediate operations such as filter() and map() to return a stream of elements that meet certain criteria.

The final operation of the stream is terminal, and no other intermediate operation can be executed after this stage on the List.

To print out elements in a LinkedList using streams, you only need to use the forEach() after the intermediate operations.

This terminal operation accepts a Consumer which is simply a functional interface with a single argument and returns no result.

In this method, we will use a LinkedList with a List of names and then filter names that start with the letter J and finally print them using the forEach() method.



Print LinkedList using toString() method

LinkedList uses toString() from its parent class AbstractCollection` class. This method returns a collection of strings of the objects in a square bracket separated by commas. Here is implementation of the method.

If you notice, it is iterating through the LinkedList and calling internally toString() method of each items in the LinkedList.

For example:
If we have LinkedList<String>, then it will call toString() method of String class for each element of the LinkedList and append it to StringBuffer.

If you are adding custom objects to the LinkedList, then you should add toString() in custom object to get meaning output while printing the LinkedList.


[introduction to java, multithreading basics, JUnit in action]

Print LinkedList using Iterator

LinkedList inherits the iterator functionality from AbstractList which implements the Iterable interface.

The iterator() returns an Iterator which allows us to print out the elements in the LinkedList using the forEachRemaining() method from the Iterator class.

The forEachRemaining() method accepts a Consumer, and the default implementation checks whether there is another element in the List and accepts it if true.

For each element iterated, the method will execute the desired operation such as printing out the elements but will throw a NullPointerException if the action is null.

We will use a LinkedList with all the vowels, return an Iterator from the List then print out the vowels using the forEachRemaining() method of the Iterator.



Print LinkedList using custom objects

In a real-life situation, you are usually required to create your custom objects used in the LinkedList compared to using String, Integer and Character and other Java reference types.

An example of a real-life situation where you will need to create custom objects includes implementing continuous stock prices, browser history, and video or image player.

Some implementations such as browser history and media players require a doubly LinkedList to enable viewing previous and next items in the List.

Implementation of continuous stock prices leverages a singly LinkedList, which you will learn how is created in this article.

We will use a Customer class with first name, last name, and email as its properties.

After creating the customer class, create a LinkedList in the main method with a List of customer instances and print out the List using the forEach() method.


Customer{firstName=’john’, lastName=’doe’, email=’[email protected]’}
Customer{firstName=’esther’, lastName=’anderson’, email=’[email protected]’}
Customer{firstName=’mary’, lastName=’public’, email=’[email protected]’}

Custom singly LinkedList

How to print a custom singly LinkedList

The Java built-in LinkedList is doubly by default, and in this article, you are going to create a custom singly LinkedList, add elements and print out the elements.

A singly LinkedList is a List that only keeps track of the next element, with the last element pointing to null.

When iterating through the List in the singly LinkedList, it throws a NullPointerException after getting to the last element. Print out the result to the console to prevent the LinkedList from throwing an Exception.

The LinkedList will hold its data and an object to the next element. We will use student objects with only the name as the data to an element in the List.

After creating the Student class, create a custom LinkedList class with the student and pointer to the next student as the properties.

Create a constructor that only accepts a student class. The student class will be used as the data for the node.

Create the main method in the SinglyLinkedList class and create 5 nodes with the first node pointing to the second, second to third, third to fourth, and fourth to fifth.

In SinglyLinkedList class, create the print student method to print out the elements in the LinkedList.

The method first checks if the first node is null and, if true, prints the List is empty to the console.

The initial student is a node that tracks the current position of the List and increments each time the check for null passes.

The students will be printed out for each node in the List, and the last element will be null to show that there are no other nodes in the LinkedList.

Finally, call the print student method in the main method after node creation and pass the first node as the parameter to the method.

Here is the complete class:




In this tutorial, you have learned the different ways that you can leverage to print out the elements of a LinkedList. The methods covered include using a for loop, enhanced for loop, streams, toString(), Iterator, custom objects, and lastly, custom singly LinkedList.

Was this post helpful?


You may also like:

Related Posts

  • 06 December

    Update Value of Key in HashMap in Java

    Table of ContentsUsing the put() Method of HashMap Collection in JavaUsing the compute() Method of HashMap Collection in JavaUsing the merge() Method of the HashMap Collection in JavaUsing the computeIfPresent() Method of The HashMap Collection in JavaUsing the replace() Method of The HashMap Collection in JavaUsing the TObjectIntHashMap Class of Gnu.Trove Package in JavaUsing the […]

  • 29 November

    Create Array of Linked Lists in Java

    Table of ContentsIntroductionLinked List in JavaApplication of Array of Linked ListsCreate Array of Linked Lists in JavaUsing Object[] array of Linked Lists in JavaUsing the Linked List array in JavaUsing the ArrayList of Linked Lists in JavaUsing the Apache Commons Collections Package Introduction In this article, we will look at how to Create an Array […]

  • 20 September

    Return ArrayList in Java

    Table of ContentsReturn ArrayList in Java From a Static MethodReturn ArrayList in Java From a Non-static MethodConclusion This article discusses cases of returning an ArrayList in Java from a method. An ArrayList in Java is a collection of elements of the same data type under a single variable name. In different cases, you can return […]

  • 17 September

    Create List with One Element in Java

    Table of ContentsUsing Collections.singletonList()Using Array.asList() method [ Immuatable list]Using new ArrayList with Array.asList() method [ Mutable list] In this post, we will see how to create List with One Element in java.. Using Collections.singletonList() This is best way to create List with single element if you need an immutable List. [crayon-63da4e68dc771695133643/] Output [crayon-63da4e68dc775964976131/] If you […]

  • 17 May

    How to Add Multiple Values for Single Key In HashMap in Java

    Table of ContentsHashMapCan HashMap Store Multiple Values AutomaticallyWays to Add Multiple Values for Single Key In HashMap in JavaUsing the Standard LibraryUsing Apache Commons LibraryUsing Google Guava LibraryUsing TreeSet as ValuesUsing a Wrapper ClassUsing Java TuplesUsing compute() Function in JDK 8Conclusion This article discusses the HashMap in Java and how to add multiple values for […]

  • java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
    22 February

    [Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

    Table of ContentsReason for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListFixes for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListUse ArrayList’s constructorAssign Arrays.asList() to List reference rather than ArrayList In this post, we will see how to fix java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList. ClassCastException is runtime exception which indicate that code has tried to […]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.