Java ArrayList.forEach() 方法及代码示例

对数组列表中的每个可迭代的元素执行操作

定义

public void forEach​(Consumer<? super E> action)

参数

参数类型参数名称参数描述
Consumer<? super E>action对每个元素都要采取的行动
类型参数E列表元素的类型

返回值

返回 void

抛出的异常

NullPointerException 如果指定的行动为 null

说明

操作会一直执行, 直到所有元素都被处理完或操作抛出异常

如果指定了迭代的顺序, 操作将按照迭代的顺序执行.

由操作引发的异常会被传递给调用者.

本方法由  Iterable<E>forEach() 指派.

示例

对数组列表使用forEach()的示例

package com.yi21.arraylist;

import java.util.ArrayList;
import java.util.Set;

public class Yi21ArraysListForEach {

    public static void main(String[] args) {
        
        ArrayList<String> list = new ArrayList<>();
        list.addAll(Set.of("Hello", "World", "21yi"));
        list.forEach(System.out::println);

        System.out.println("-".repeat(20));

        ArrayList<Integer> iList = new ArrayList<>();
        iList.addAll(Set.of(1, 2, 3, 21));
        iList.forEach((Integer i) -> { System.out.println(i * i);});

    }

}

执行结果为 :

Hello
21yi
World
--------------------
4
1
441
9