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.

Output:

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.

Output:

20
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.

Output:

james
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.

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.

Output:

[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.

Output:

A
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.

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.

Output:

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:

Output:

Student{name=’mary’}
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.


import_contacts

You may also like:

Related Posts

  • 10 September

    How to remove element from Arraylist in java while iterating

    Table of ContentsIntroductionUsing Collection’s removeIf() methodUsing ListIterator classUsing removeAll() methodUsing Java 8 Stream to filter List itemsConclusion Introduction In this tutorial, you will learn how to remove element from Arraylist in java while iterating using different implementations provided by Java. It is necessary to understand the right way to remove items from a List because […]

  • Print HashMap in java
    30 June

    Print HashMap in Java

    Table of ContentsPrint from the HashMap ReferencePrint HashMap using foreach method with keyset()Print HashMap using Consumer with entrySet()Print HashMap using Arrays’s asList() methodPrint HashMap using Collections’s singletonList()Print HashMap using getkey() and getValue with entrySet()Print HashMap using BiConsumerPrint HashMap using IteratorPrint HashMap using custom ObjectsConclusion In this article, we will see how to print HashMap in […]

  • Java Set to Array
    12 May

    Java Set to Array

    Table of Contents1. Using Java 8’s Stream2. Using toArray()3. Using toArray(IntFunction) [Java 11]4. Using System.arraycopy()5. Using Arrays.copyOf6. Using simple iteration7. Using Guava library7.1 Using FluentIterable7.2 Using Iterables In this post, we will learn java set to array conversion. There are many ways to convert set to an array. 1. Using Java 8’s Stream If you […]

  • Print ArrayList in java
    11 May

    Print ArrayList in Java

    Learn about how to print ArrayList in java in different ways.

  • 15 April

    How to Deep Copy Arraylist in Java

    Learn about how to create deep copy of ArrayList in different ways.

  • 02 October

    Initialize ArrayList with values in Java

    Table of ContentsUsing Arrays.asList()Initialize ArrayList with String valuesintialize ArrayList with Integer valuesintialize ArrayList with float valuesUsing Stream in Java 8Using Factory Method in java 9Using double braces In this article, we will learn to initialize ArrayList with values in Java. ArrayList is an implementation class of List interface in Java. It is used to store […]

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.