Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the difference between list.forEach () and list.stream (). ForEach () in java

Shulou Source: shulou.com Published: 2022-06-01 05:34:10 09月27日 Update

This article mainly introduces the relevant knowledge of what is the difference between list.forEach () and list.stream (). ForEach () in java, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe that you will gain something after reading the difference between list.forEach () and list.stream (). ForEach () in this java, let's take a look at it.

First of all, their function is to traverse each element of the array and execute the accept () method of the input parameter, but they are implemented in a different way, and in some specific cases, the execution will produce different results.

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

Overview

First, create a list of iterations:

List list = Arrays.asList ("A", "B", "C", "D")

The most direct approach is to use an enhanced for loop:

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

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

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

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

List.stream () forEach (consumer)

Both versions iterate through 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 enhanced for loops

Default void forEach (Consumer

Tags: Knowledge iteration element content situation array method article result loop different subtle same two value example function function only difference Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Docker Xiaomi Shulou Information Microsoft