Java 8 – forEach with Index

Introduction

In Java 8, the forEach() method is commonly used to iterate over collections in a concise and functional style. However, the forEach() method does not directly provide access to the index of the current element. To achieve iteration with an index, you need to use additional techniques.

In this guide, we will explore how to use forEach() in Java 8 to print elements with their index in a list.

Solution Steps

  1. Define the List: Create a list of elements to iterate over.
  2. Use an AtomicInteger for Index: Use an external counter such as AtomicInteger to keep track of the index.
  3. Iterate with forEach(): Use the forEach() method, incrementing the index on each iteration.
  4. Print the Element with its Index: Display the current element along with its index.

Java Program

Method 1: Using AtomicInteger

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class ForEachWithIndex {
    public static void main(String[] args) {
        // Step 1: Define the list
        List<String> items = Arrays.asList("Apple", "Banana", "Orange", "Mango");

        // Step 2: Use AtomicInteger to keep track of the index
        AtomicInteger index = new AtomicInteger(0);

        // Step 3: Use forEach and print the index with each element
        items.forEach(item -> {
            System.out.println("Index: " + index.getAndIncrement() + ", Item: " + item);
        });
    }
}

Output

Index: 0, Item: Apple
Index: 1, Item: Banana
Index: 2, Item: Orange
Index: 3, Item: Mango

Explanation

  • Step 1: We define a list of strings containing different fruit names.
  • Step 2: We use AtomicInteger to keep track of the index, starting from 0. The AtomicInteger is used because it is mutable and can be safely incremented inside the lambda expression.
  • Step 3: Inside the forEach() method, we print both the current index and the element by calling index.getAndIncrement(). This increments the index with each iteration.

Method 2: Using IntStream for Index

Another way to access the index during iteration is by using IntStream to generate the indexes and forEach() to access the elements.

import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;

public class ForEachWithIndexUsingIntStream {
    public static void main(String[] args) {
        // Step 1: Define the list
        List<String> items = Arrays.asList("Apple", "Banana", "Orange", "Mango");

        // Step 2: Use IntStream to generate indexes
        IntStream.range(0, items.size())
            .forEach(i -> System.out.println("Index: " + i + ", Item: " + items.get(i)));
    }
}

Output

Index: 0, Item: Apple
Index: 1, Item: Banana
Index: 2, Item: Orange
Index: 3, Item: Mango

Explanation

  • Step 1: We define the same list of fruit names.
  • Step 2: IntStream.range(0, items.size()) generates a stream of integers from 0 to the size of the list. We then use forEach() to print the index and the corresponding element from the list using items.get(i).

Conclusion

In Java 8, there is no direct way to get the index inside the forEach() method, but you can use AtomicInteger or IntStream to achieve this functionality. The first approach uses an external counter to track the index, while the second approach uses a stream of integers to access both the index and the elements in the list. Both methods are effective, and you can choose the one that best fits your needs.

Comments