foreach()方法

119 阅读1分钟

foreach()方法是Java8新增的方法用来遍历MapList

foreach()遍历List

public class Test {
    public static void main(String[] args) {
        ArrayList<Integer> intList=new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            intList.add(i);
        }
        intList.forEach(new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) {
                System.out.print(integer+"=");
            }
        });
    }
}

输出结果:

foreach()遍历Map

public class Test {
    public static void main(String[] args) {
        HashMap<Integer,Integer>map=new HashMap<>();
        for (int i = 0; i < 10; i++) {
            map.put(i,i+1);
        }
        map.forEach(new BiConsumer<Integer, Integer>() {
            @Override
            public void accept(Integer integer, Integer integer2) {
                System.out.println("key"+integer+"value"+integer2);
            }
        });
    }
}

输出结果:

BiConsumer和Consumer

从源码可以看到这两个是一个函数式接口

函数式接口:接口中只有一个抽象方法的接口,称为函数式接口; 可以使用@FunctionalInterface注解修饰,对该接口做检查;如果接口里,有多个抽象类,使用该注解,会有语法错误。

在java8中,lambda表达式所用的接口,必须是函数式接口;