Table of Contents
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class PrintLinkedList public static void main(String args[]) { // using for loop LinkedList<String> domesticAnimals = new LinkedList<>( List.of("cow", "hen", "goat", "sheep", "donkey")); for (int i = 0; i < domesticAnimals.size(); i++) { System.out.println(i +" = "+domesticAnimals.get(i)); } } } |
Output:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class PrintLinkedList public static void main(String args[]) { // using enhanced for loop LinkedList<Integer> numbers = new LinkedList<>(List.of(20,45,80,36,27,100)); for (Integer integer : numbers) { System.out.println(integer); } } } |
Output:
45
80
36
27
100
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
public class PrintLinkedList public static void main(String args[]) { //using streams LinkedList<String> names = new LinkedList<>(List.of("esther","abdul","james","mary","jamal")); names.stream() .filter(s -> s.startsWith("j")) .forEach(System.out::println); } } |
Output:
jamal
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
/** * Returns a string representation of this collection. The string * representation consists of a list of the collection's elements in the * order they are returned by its iterator, enclosed in square brackets * (<tt>"[]"</tt>). Adjacent elements are separated by the characters * <tt>", "</tt> (comma and space). Elements are converted to strings as * by {@link String#valueOf(Object)}. * * @return a string representation of this collection */ public String toString() { Iterator<E> it = iterator(); if (! it.hasNext()) return "[]"; StringBuilder sb = new StringBuilder(); sb.append('['); for (;;) { E e = it.next(); sb.append(e == this ? "(this Collection)" : e); if (! it.hasNext()) return sb.append(']').toString(); sb.append(',').append(' '); } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class PrintLinkedList public static void main(String args[]) { //using toString() method LinkedList<String> courses = new LinkedList<>(List.of( "introduction to java", "multithreading basics", "JUnit in action" )); System.out.println(courses.toString()); } } |
Output:
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.
1 2 3 4 5 6 7 8 9 10 11 |
public class PrintLinkedList public static void main(String args[]) { //using Iterator LinkedList<Character> vowels = new LinkedList<>(List.of('A','E','I','O','U')); Iterator<Character> iterator = vowels.iterator(); iterator.forEachRemaining(System.out::println); } } |
Output:
E
I
O
U
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// customer class class Customer{ private String firstName; private String lastName; private String email; public Customer(String firstName, String lastName, String email) { this.firstName = firstName; this.lastName = lastName; this.email = email; } // Generate Getters, Setters and toString() } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class PrintLinkedList public static void main(String args[]) { //print LinkedList with custom objects LinkedList<Customer> customers = new LinkedList<>(List.of( )); customers.forEach(System.out::println); } } |
Output:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class Student{ private String name; public Student(String name) { this.name = name; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + '}'; } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
public class SinglyLinkedList { private Student student; private SinglyLinkedList nextStudent; public SinglyLinkedList(Student student) { this.student = student; this.nextStudent = null; } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
SinglyLinkedList firstStudent = new SinglyLinkedList(new Student("abdul")); SinglyLinkedList secondStudent = new SinglyLinkedList(new Student("bilal")); SinglyLinkedList thirdStudent = new SinglyLinkedList(new Student("canon")); SinglyLinkedList fourthStudent = new SinglyLinkedList(new Student("doreen")); SinglyLinkedList fifthStudent = new SinglyLinkedList(new Student("eden")); firstStudent.nextStudent = secondStudent; secondStudent.nextStudent = thirdStudent; thirdStudent.nextStudent = fourthStudent; fourthStudent.nextStudent = fifthStudent; |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public static void printStudents(SinglyLinkedList firstStudent){ SinglyLinkedList initialStudent; if (firstStudent == null){ System.out.println("the list is empty"); } initialStudent = firstStudent; while (initialStudent != null){ System.out.println(initialStudent.student); initialStudent = initialStudent.nextStudent; } System.out.println(initialStudent); } |
Finally, call the print student method in the main method after node creation and pass the first node as the parameter to the method.
1 2 3 |
printStudents(firstStudent); |
Here is the complete class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
package org.arpit.java2blog.entry; public class SinglyLinkedList { private Student student; private SinglyLinkedList nextStudent; public SinglyLinkedList(Student student) { this.student = student; this.nextStudent = null; } public static void main(String[] args) { SinglyLinkedList firstStudent = new SinglyLinkedList(new Student("abdul")); SinglyLinkedList secondStudent = new SinglyLinkedList(new Student("bilal")); SinglyLinkedList thirdStudent = new SinglyLinkedList(new Student("canon")); SinglyLinkedList fourthStudent = new SinglyLinkedList(new Student("doreen")); SinglyLinkedList fifthStudent = new SinglyLinkedList(new Student("eden")); firstStudent.nextStudent = secondStudent; secondStudent.nextStudent = thirdStudent; thirdStudent.nextStudent = fourthStudent; fourthStudent.nextStudent = fifthStudent; printStudents(firstStudent); } public static void printStudents(SinglyLinkedList firstStudent){ SinglyLinkedList initialStudent; if (firstStudent == null){ System.out.println("the list is empty"); } initialStudent = firstStudent; while (initialStudent != null){ System.out.println(initialStudent.student); initialStudent = initialStudent.nextStudent; } System.out.println(initialStudent); } } |
Output:
Student{name=’bilal’}
Student{name=’susan’}
Student{name=’doreen’}
Student{name=’eden’}
null
Conclusion
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.