Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

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

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report