Home  >  Article  >  Java  >  What is the difference between list.forEach() and list.stream().forEach() in Java?

What is the difference between list.forEach() and list.stream().forEach() in Java?

WBOY
WBOYforward
2023-04-24 22:07:061540browse

First of all, their functions are to traverse each element of the array and execute the accept() method of the input parameters, but their implementation methods are different. In some specific cases, the execution will produce different results.

In most cases, both will produce the same results, however, we will see some subtle differences.

Overview

First, create an iterable list:

List<String> list = Arrays.asList("A","B","C","D");

The most straightforward way is to use an enhanced for loop:

for(String s : list"){
    //something
}

If we want to use a function In Java, we can also use forEach(). We can do this directly on the collection:

Consumer<String> consumer = s -> {System.out::println};
list.forEach(consumer);

Alternatively, we can call forEach() on the collection's stream:

list.stream().forEach(consumer);

Both versions will iterate over the list and print all elements:

ABCD ABCD

In this simple example, there is no difference in the forEach() we use.

Difference

list.forEach() uses an enhanced for loop

default void forEach(Consumer<? super T> action) {
      Objects.requireNonNull(action);
      for (T t : this) {
          action.accept(t);
      }
  }

list.stream().forEach(): It first converts the collection to a stream, and then Iterate the stream

When deleting while traversing, forEach can fail quickly, and stream().forEach() will only wait until the array is traversed before throwing an exception

public class DeleteDifference {
   public static void main(String[] args) {
       List<String> list = Arrays.asList("A", "B", "C", "D");

       try {
           list.forEach(item -> {
               System.out.println(item);
               list.remove(0);
           });
       } catch (Exception e) {
           e.printStackTrace();
       }

       list.stream().forEach(item -> {
           System.out.println(item);
           list.remove(0); 
       });
   }
}

The above is the detailed content of What is the difference between list.forEach() and list.stream().forEach() in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete