Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java ArrayList forEach() Method

Java ArrayList forEach() Method

Java ArrayList Java ArrayList

The forEach() method is used to traverse every element in the dynamic array and perform a specific action.

The syntax of the forEach() method is:


arraylist.forEach(Consumer action)

**Note:** arraylist is an object of the ArrayList class.

Parameter Description:

Return Value

No value is returned.

Example

Multiply all elements by 10:

Example

import

java.util.ArrayList

;

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create an array

        ArrayList

<

Integer

numbers

=

new

ArrayList

<>

(

)

;

       

// Add elements to the array

        numbers.

add

(

1

)

;

        numbers.

add

(

2

)

;

        numbers.

add

(

3

)

;

        numbers.

add

(

4

)

;

       

System

.

out

.

println

(

"ArrayList: "

numbers

)

;

       

// Multiply all elements by 10

       

System

.

out

.

print

(

"Updated ArrayList: "

)

;

       

       

// Pass the lambda expression to forEach

        numbers.

forEach

(

(

e

)

->

{

            e

=

e

10

;

           

System

.

out

.

print

(

e

" "

)

;

       

}

)

;

   

}

}

The output of the above program is:


ArrayList: [1, 2, 3, 4]
更新 ArrayList: 10 20 30 40 

In the example above, we created a dynamic array named numbers.

Note this line:


numbers.forEach((e) -> {
    e = e * 10;
    System.out.print(e + " ");  
});

In the example above, we passed the expression of the anonymous function lambda as a parameter to the forEach() method; the lambda expression multiplies each element in the dynamic array by 10 and then outputs the result.

For more information about lambda expressions, please visit Java Lambda expression.

**Note:** The forEach() method is different from the for-each loop.Java for-each It is used to traverse each element in the array.

Java ArrayList Java ArrayList