How to iterate List Using Streams in Java?

JavaObject Oriented ProgrammingProgramming

The List interface extends the Collection interface and stores a sequence of elements. The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list. Unlike sets, the list allows duplicate elements, and allows multiple null values if a null value is allowed in the list.

You can use stream() method of the List interface which gives a stream to iterate using forEach method. In forEach method, we can use the lambda expression to iterate over all elements. The following code snippet shows the usage of streams to iterate over the list.

list.stream().forEach(i -> {System.out.print(i + " ");});

In this article, we're discussing the use of streams to iterate a list in given examples.

Example 1

Following is the example showing the use of stream API to iterate the list of string −

package com.tutorialspoint;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
      list.stream().forEach(i -> {System.out.print(i + " ");});
   }
}

Output

This will produce the following result −

A B C D

Example 2

Following is the example showing the use of stream API to iterate the list of numbers −

package com.tutorialspoint;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
      list.stream().forEach(i -> {System.out.print(i + " ");});
   }
}

Output

This will produce the following result −

1 2 3 4
raja
Updated on 26-May-2022 13:23:21

Advertisements