非原創(chuàng)辕万,知識(shí)總結(jié)性文章
package com.taotao.springboot;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;
public class IterableForEachExample {
public static void main(String[] args) {
List<Integer> ints = new ArrayList<>();
for (int i = 0; i < 10; i++) ints.add(i);
//迭代器遍歷
Iterator<Integer> iterator = ints.iterator();
while (iterator.hasNext()) {
Integer i = iterator.next();
System.out.println("Iterator Value::" + i);
}
//使用forEach方法遍歷,這里使用了匿名內(nèi)部類
ints.forEach(new Consumer<Integer>() {
public void accept(Integer t) {
System.out.println("forEach anonymous class Value::" + t);
}
});
//通過(guò)實(shí)現(xiàn)Consumer接口的子類遍歷千元,業(yè)務(wù)處理從遍歷邏輯中抽取出來(lái)
MyConsumer action = new MyConsumer();
ints.forEach(action);
}
}
//實(shí)現(xiàn)Conumer接口
class MyConsumer implements Consumer<Integer> {
public void accept(Integer t) {
System.out.println("Consumer impl Value::" + t);
}
}
通過(guò)上面這個(gè)例子震肮,看出使用 forEach()方法代碼行數(shù)會(huì)增加筝蚕,但是它將遍歷邏輯與業(yè)務(wù)處理邏輯分離,有助于我們將關(guān)注點(diǎn)放在業(yè)務(wù)邏輯的處理上