Iterating Over LinkedList in Java

A LinkedList is a doubly linked list implementation of the List and Deque interfaces. This guide will provide examples of how to iterate over a LinkedList using different methods, including detailed explanations and outputs. Additionally, it will cover how to iterate over a LinkedList containing custom objects.

Table of Contents

  1. Introduction
  2. Using For-Loop
  3. Using Enhanced For-Loop
  4. Using Iterator
  5. Using ListIterator
  6. Using forEach Method (Java 8)
  7. Using Stream API (Java 8)
  8. Iterating Over a LinkedList with Custom Objects
  9. Conclusion

1. Introduction

A LinkedList is a part of the Java Collections Framework and is an implementation of the List and Deque interfaces. It is useful for scenarios where you need a list that supports efficient insertion and removal of elements.

2. Using For-Loop

The traditional for-loop is a basic and flexible way to iterate over a LinkedList.

Example: Using For-Loop

import java.util.LinkedList;
import java.util.List;

public class ForLoopExample {
    public static void main(String[] args) {
        List<String> fruits = new LinkedList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        for (int i = 0; i < fruits.size(); i++) {
            System.out.println(fruits.get(i));
        }
    }
}

Output:

Apple
Banana
Orange

3. Using Enhanced For-Loop

The enhanced for-loop (or for-each loop) provides a simpler and more readable way to iterate over a LinkedList.

Example: Using Enhanced For-Loop

import java.util.LinkedList;
import java.util.List;

public class EnhancedForLoopExample {
    public static void main(String[] args) {
        List<String> fruits = new LinkedList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

Output:

Apple
Banana
Orange

4. Using Iterator

The Iterator provides a way to iterate over the elements and allows element removal during iteration if needed.

Example: Using Iterator

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class IteratorExample {
    public static void main(String[] args) {
        List<String> fruits = new LinkedList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        Iterator<String> iterator = fruits.iterator();
        while (iterator.hasNext()) {
            String fruit = iterator.next();
            System.out.println(fruit);
        }
    }
}

Output:

Apple
Banana
Orange

5. Using ListIterator

The ListIterator provides additional functionality compared to the Iterator, such as bidirectional traversal and modification of elements.

Example: Using ListIterator

import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class ListIteratorExample {
    public static void main(String[] args) {
        List<String> fruits = new LinkedList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        ListIterator<String> listIterator = fruits.listIterator();
        while (listIterator.hasNext()) {
            String fruit = listIterator.next();
            System.out.println(fruit);
        }

        System.out.println("Reverse Iteration:");
        while (listIterator.hasPrevious()) {
            String fruit = listIterator.previous();
            System.out.println(fruit);
        }
    }
}

Output:

Apple
Banana
Orange
Reverse Iteration:
Orange
Banana
Apple

6. Using forEach Method (Java 8)

The forEach method is part of the Java 8 Stream API and provides a functional approach to iteration.

Example: Using forEach Method

import java.util.LinkedList;
import java.util.List;

public class ForEachMethodExample {
    public static void main(String[] args) {
        List<String> fruits = new LinkedList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        // Using forEach with lambda expression
        fruits.forEach(fruit -> System.out.println(fruit));

        // Using forEach with method reference
        fruits.forEach(System.out::println);
    }
}

Output:

Apple
Banana
Orange

7. Using Stream API (Java 8)

The Stream API provides a powerful way to process sequences of elements, including iteration.

Example: Using Stream API

import java.util.LinkedList;
import java.util.List;

public class StreamAPIExample {
    public static void main(String[] args) {
        List<String> fruits = new LinkedList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        // Using stream and forEach
        fruits.stream().forEach(fruit -> System.out.println(fruit));

        // Using parallel stream and forEach
        fruits.parallelStream().forEach(fruit -> System.out.println("Parallel: " + fruit));
    }
}

Output:

Apple
Banana
Orange
Parallel: Apple
Parallel: Banana
Parallel: Orange

8. Iterating Over a LinkedList with Custom Objects

When dealing with custom objects in a LinkedList, you can iterate over the list similarly to how you would with built-in types. Here is an example using a custom Person class.

Custom Object Example: Using Enhanced For-Loop

import java.util.LinkedList;
import java.util.List;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + '}';
    }
}

public class CustomObjectExample {
    public static void main(String[] args) {
        List<Person> persons = new LinkedList<>();
        persons.add(new Person("Alice", 30));
        persons.add(new Person("Bob", 25));
        persons.add(new Person("Charlie", 35));

        // Using Enhanced For-Loop
        System.out.println("Using Enhanced For-Loop:");
        for (Person person : persons) {
            System.out.println(person);
        }

        // Using Iterator
        System.out.println("\nUsing Iterator:");
        Iterator<Person> iterator = persons.iterator();
        while (iterator.hasNext()) {
            Person person = iterator.next();
            System.out.println(person);
        }

        // Using forEach Method (Java 8)
        System.out.println("\nUsing forEach Method (Java 8):");
        persons.forEach(person -> System.out.println(person));

        // Using Stream API (Java 8)
        System.out.println("\nUsing Stream API (Java 8):");
        persons.stream().forEach(person -> System.out.println(person));
    }
}

Output:

Using Enhanced For-Loop:
Person{name='Alice', age=30}
Person{name='Bob', age=25}
Person{name='Charlie', age=35}

Using Iterator:
Person{name='Alice', age=30}
Person{name='Bob', age=25}
Person{name='Charlie', age=35}

Using forEach Method (Java 8):
Person{name='Alice', age=30}
Person{name='Bob', age=25}
Person{name='Charlie', age=35}

Using Stream API (Java 8):
Person{name='Alice', age=30}
Person{name='Bob', age=25}
Person{name='Charlie', age=35}

9. Conclusion

In this guide, we covered various methods to iterate over a LinkedList in Java:

  • Using For-Loop: Basic and flexible method.
  • Using Enhanced For-Loop: Simplifies code and improves readability.
  • Using Iterator: Allows element removal during iteration.
  • Using ListIterator: Supports bidirectional traversal and modification of elements.
  • Using forEach Method (Java 8): Provides a functional programming approach.
  • Using Stream API (Java 8): Offers powerful operations for processing sequences of elements, including parallel processing.

Additionally, we demonstrated how to iterate over a LinkedList containing custom objects, ensuring proper handling and display of object attributes.

By following the steps and examples provided, you should now be able to efficiently iterate over LinkedLists in your Java applications and choose the iteration method that best fits your needs.

Comments