下面通过一段代码来简单介绍一下lambda表达式
public static void main(String[] args) {
int[] array = {1, 6, 9, 6, 5};
/**
* 我们在forEach()的参数中传入IntConsumer的实现类,可以理解为函数接
* 口只有一个方法,实现类的对象只会调用那一个实现的方法,所以参数的
* action会去找到那个方法去action.那个方法
*/
Arrays.stream(array).forEach(new IntConsumerImpl());
/**
* 这里是创建了一个接口的隐式对象,但是需要我们实现里面的方法它才能
* 创建,与上面类似,会通过action.那个方法去实现
*/
Arrays.stream(array).forEach(new IntConsumer() {
@Override
public void accept(int value) {
System.out.println(value);
}
});
/**
* 函数式的编程,从上面的过程演化而来,
*
*/
Arrays.stream(array).forEach(x -> {
x++;
System.out.println(x);
});
long count = Arrays.stream(array).filter(x -> x > 5).count();
System.out.println(count);
}
Arrays中的forEach()方法:
//需要传入一个IntConsumer 类型的参数
void forEach(IntConsumer action);
方法的引用:
public static void main(String[] args) {
int[] array = {1,2,3};
// 通过对象可以找到里面的方法
Arrays.stream(array).forEach(System.out::println);
}