今天就跟大家聊聊有关Java8中怎么实现函数入参,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
1. 前情回顾
Java8支持将函数作为参数传递到另一个函数内部,在第一篇学习笔记中也简单提到了这个用法。但是在第一篇学习的时候,还是困惑的,先说下我的困惑。
在第一篇中提到函数入参,入参的类型要先定义一个接口:
public interface Predicate<T> {
boolean test(T t);
}
然后定义一个函数如下:
public static List<Apple> filterApples(List<Apple> inventory,Predicate<Apple> predicate){
List<Apple> result = new ArrayList<>();
for(Apple apple:inventory){
if(predicate.test(apple)){
result.add(apple);
}
}
return result;
}
最后调用该方法:
List<Apple> filterGreenApples= filterApples(originApples,Apple::isGreenApple);
这里问题就来了,入参类型是一个接口Predicate,那实际入参不应该是这个接口的实现类的对象吗,为什么直接就传了这个静态方法呢?
带着这个问题,开始再继续学习一下函数入参这块内容。
2. 继续学习
要理清函数作为参数传递这块内容,还得先从最简单的实现看起。在学习设计模式的时候,有了解过策略模式。第一个文章苹果那个demo为例,加上策略模式。
首先定义一个接口,后面实现的所有策略都基于该接口:
public interface ApplePredicate<T> {
boolean test(T t);
}
接着实现两个筛选苹果的策略:一个是根据颜色进行筛选,另一个是根据重量进行筛选:
public class filterAppleByColorPredicate implements Predicate<Apple> {
@Override
public boolean test(Apple apple) {
return "green".equals(apple.getColor());
}
}
public class filterAppleByWeightPredicate implements Predicate<Apple> {
@Override
public boolean test(Apple apple) {
return apple.getWeight() > 15;
}
}
最后main方法实现如下:
public static void main(String[] args){
List<Apple> inventory = ...;
// 选择根据颜色过滤的策略过滤
ApplePredicate colorPredicate = new filterAppleByColorPredicate();
filterApples(inventory,colorPredicate);
// 选择根据重量过滤的策略过滤
ApplePredicate weightPredicate = new filterAppleByWeightPredicate();
filterApples(inventory,weightPredicate);
}
public static List<Apple> filterApples(List<Apple> inventory,ApplePredicate<Apple> predicate){
List<Apple> result = new ArrayList<>();
for(Apple apple:inventory){
if(predicate.test(apple)){
result.add(apple);
}
}
return result;
}
这样就实现了一个基于策略模式的代码。
3. 匿名类
在第二小节的基础上,直接使用匿名类,省去了各种策略的实现类的定义:
filterApples(inventory,new ApplePredicate<Apple>() {
public boolean test(Apple apple){
return "green".equals(apple.getColor());
}
});
4. Lambda表达式
第三小节使用匿名类,但是当代码量多了以后,还是显得累赘,为此引入Lambda表达式来简化编写:
filterApples(inventory,(Apple apple) -> "green".equals(apple.getColor()));
关于Lambda这里我还是有疑问的,假如接口定义了两个方法:
public interface ApplePredicate<T> {
boolean test(T t);
boolean test2(T t);
}
看完上述内容,你们对Java8中怎么实现函数入参有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注天达云行业资讯频道,感谢大家的支持。