Bootstrap

forEach()

解释:forEach() 方法用于遍历动态数组中每一个元素并执行特定操作。

语法:arraylist.forEach(Consumer<E> action)

example:

ArrayList<Integer> numbers = new ArrayList<>();

        // 往数组中添加元素
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);
        System.out.println("ArrayList: " + numbers);

        // 所有元素乘以 10
        System.out.print("更新 ArrayList: ");

        // 将 lambda 表达式传递给 forEach
        numbers.forEach((c) -> {
            c = c * 10;
            System.out.print(c + " ");
        });

输出如下:

那和for循环到底有啥区别呢?

先来看下for循环的用法

 for(Integer i:numbers){
            i = i * 10;
            System.out.print(i + " ");
        }

输出和上面一样。

那两者到底有何区别呢?

1.for循环是可以中断循环(利用break语句或return语句),但forEach不可以中断循环。

2.网上说循环ArrayList时,普通for循环比foreach循环花费的时间要少一点;循环LinkList时,普通for循环比foreach循环花费的时间要多很多。

一段简单的代码比较耗时:

 long arrayForStartTime1 = System.currentTimeMillis();
        numbers.forEach((c) -> {
            c = c * 10;
            System.out.print(c + " ");
        });
        long arrayForEndTime1 = System.currentTimeMillis();
        System.out.println("采用forEach循环的耗时为"+(arrayForEndTime1 - arrayForStartTime1));



        long arrayForStartTime = System.currentTimeMillis();
        for(Integer i:numbers){
            i = i * 10;
            System.out.print(i + " ");
        }
        long arrayForEndTime = System.currentTimeMillis();
        System.out.println("采用for循环的耗时为"+(arrayForEndTime - arrayForStartTime));

;