温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java8中怎么实现函数入参

发布时间:2021-07-14 13:52:17 来源:亿速云 阅读:570 作者:Leah 栏目:大数据

今天就跟大家聊聊有关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中怎么实现函数入参有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI