登录  /  注册
首页 > Java > java教程 > 正文

java8中predicate的用法介绍(代码示例)

不言
发布: 2019-02-21 14:13:06
转载
6324人浏览过

本篇文章给大家带来的内容是关于java8中predicate的用法介绍(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

传递代码

我们首先看一个例子,假设你有一个 apple 类,它有一个getcolor方法,还有一个变量inventory保存着一个apples的列表。你可能想要选出所有的绿苹果,并返回一个列表。通常我们用筛选(filter)一词来表达这个概念。在java 8之前,你可能会写这样一个方法 filtergreenapples :

public static List<apple> filterGreenApples(List<apple> inventory){
List<apple> result = new ArrayList();
for (Apple apple: inventory){
if ("green".equals(apple.getColor())) {
result.add(apple);
        }
    }
return result;
}</apple></apple></apple>
登录后复制

但是接下来,有人可能想要选出重的苹果,比如超过150克,于是你心情沉重地写了下面这
个方法,甚至用了复制粘贴:

public static List<apple> filterHeavyApples(List<apple> inventory){
List<apple> result = new ArrayList();
for (Apple apple: inventory){
if (apple.getWeight() &gt; 150) {
result.add(apple);
        }      
    }
return result;
}</apple></apple></apple>
登录后复制

我们都知道软件工程中复制粘贴的危险——给一个做了更新和修正,却忘了另一个。嘿,这
两个方法只有一行不同: if 里面高亮的那行条件。如果这两个高亮的方法之间的差异仅仅是接受
的重量范围不同,那么你只要把接受的重量上下限作为参数传递给 filter 就行了,比如指定
(150, 1000) 来选出重的苹果(超过150克),或者指定 (0, 80) 来选出轻的苹果(低于80克)。
但是,我们前面提过了,Java 8会把条件代码作为参数传递进去,这样可以避免 filter 方法
出现重复的代码。现在你可以写:

public static boolean isGreenApple(Apple apple) {
    return "green".equals(apple.getColor());
}
public static boolean isHeavyApple(Apple apple) {
    return apple.getWeight() &gt; 150;
}
static List<apple> filterApples(List<apple> inventory, Predicate<apple> p) {
    List<apple> result = new ArrayList();
    for (Apple apple: inventory){
        if (p.test(apple)) {
            result.add(apple);
        }
    }
    return result;
}</apple></apple></apple></apple>
登录后复制

要用它的话,你可以写:
filterApples(inventory, Apple::isGreenApple);
或者
filterApples(inventory, Apple::isHeavyApple);
什么是谓词?

前面的代码传递了方法 Apple::isGreenApple (它接受参数 Apple 并返回一个
boolean )给 filterApples ,后者则希望接受一个 Predicate 参数。词 谓词(predicate)
在数学上常常用来代表一个类似函数的东西,它接受一个参数值,并返回 true 或 false 。你
在后面会看到,Java 8也会允许你写 Function ——在学校学过函数却没学
过谓词的读者对此可能更熟悉,但用 Predicate 是更标准的方式,效率也会更高一
点儿,这避免了把 boolean 封装在 Boolean 里面。
从传递方法到 Lambda

把方法作为值来传递显然很有用,但要是为类似于 isHeavyApple 和 isGreenApple 这种可
能只用一两次的短方法写一堆定义有点儿烦人。不过Java 8也解决了这个问题,它引入了一套新
记法(匿名函数或Lambda),让你可以写
filterApples(inventory, (Apple a) -> "green".equals(a.getColor()) );
或者
filterApples(inventory, (Apple a) -> a.getWeight() > 150 );
甚至
filterApples(inventory, (Apple a) -> a.getWeight() "brown".equals(a.getColor()) );
完整的代码为:

public class FilteringApples1 {
    public static void main(String[] args) {
        List<filteringapples1.apple> inventory = Arrays.asList(new FilteringApples1.Apple(80, "green"),
                new FilteringApples1.Apple(155, "green"),
                new FilteringApples1.Apple(120, "red"));

        List<filteringapples1.apple> greenApples2 = filterApples(inventory, (FilteringApples1.Apple a) -&gt; "green".equals(a.getColor()));
        System.out.println(greenApples2);

        // [Apple{color='green', weight=155}]
        List<filteringapples1.apple> heavyApples2 = filterApples(inventory, (FilteringApples1.Apple a) -&gt; a.getWeight() &gt; 150);
        System.out.println(heavyApples2);

        // []
        List<filteringapples1.apple> weirdApples = filterApples(inventory, (FilteringApples1.Apple a) -&gt; a.getWeight()  filterApples(List<filteringapples1.apple> inventory, Predicate<filteringapples1.apple> p) {
        List<filteringapples1.apple> result = new ArrayList();
        for (FilteringApples1.Apple apple : inventory) {
            if (p.test(apple)) {
                result.add(apple);
            }
        }
        return result;
    }

    public static class Apple {
        private int weight = 0;
        private String color = "";

        public Apple(int weight, String color) {
            this.weight = weight;
            this.color = color;
        }

        public Integer getWeight() {
            return weight;
        }

        public void setWeight(Integer weight) {
            this.weight = weight;
        }

        public String getColor() {
            return color;
        }

        public void setColor(String color) {
            this.color = color;
        }

        public String toString() {
            return "Apple{" +
                    "color='" + color + '\'' +
                    ", weight=" + weight +
                    '}';
        }
    }

}</filteringapples1.apple></filteringapples1.apple></filteringapples1.apple></filteringapples1.apple></filteringapples1.apple></filteringapples1.apple></filteringapples1.apple>
登录后复制

java8中内置filter函数

static <t> Collection<t> filter(Collection<t> c, Predicate<t> p);</t></t></t></t>
登录后复制

这样你甚至都不需要写 filterApples 了,因为比如先前的调用

filterApples(inventory, (Apple a) -&gt; a.getWeight() &gt; 150 );
登录后复制

就可以直接调用库方法 filter :

filter(inventory, (Apple a) -&gt; a.getWeight() &gt; 150 );
登录后复制

以上就是java8中predicate的用法介绍(代码示例)的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:segmentfault网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号