java 谓词_java8-谓词(predicate)

传递代码

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

public static List filterGreenApples(List inventory){

List result = new ArrayList<>();

for (Apple apple: inventory){

if ("green".equals(apple.getColor())) {

result.add(apple);

}

}

return result;

}

但是接下来,有人可能想要选出重的苹果,比如超过150克,于是你心情沉重地写了下面这

个方法,甚至用了复制粘贴:

public static List filterHeavyApples(List inventory){

List result = new ArrayList<>();

for (Apple apple: inventory){

if (apple.getWeight() > 150) {

result.add(apple);

}

}

return result;

}

我们都知道软件工程中复制粘贴的危险——给一个做了更新和修正,却忘了另一个。嘿,这

两个方法只有一行不同: 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() > 150;

}

static List filterApples(List inventory, Predicate p) {

List result = new ArrayList<>();

for (Apple apple: inventory){

if (p.test(apple)) {

result.add(apple);

}

}

return result;

}

要用它的话,你可以写:

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() < 80 ||

"brown".equals(a.getColor()) );

完整的代码为:

public class FilteringApples1 {

public static void main(String[] args) {

List inventory = Arrays.asList(new FilteringApples1.Apple(80, "green"),

new FilteringApples1.Apple(155, "green"),

new FilteringApples1.Apple(120, "red"));

List greenApples2 = filterApples(inventory, (FilteringApples1.Apple a) -> "green".equals(a.getColor()));

System.out.println(greenApples2);

// [Apple{color='green', weight=155}]

List heavyApples2 = filterApples(inventory, (FilteringApples1.Apple a) -> a.getWeight() > 150);

System.out.println(heavyApples2);

// []

List weirdApples = filterApples(inventory, (FilteringApples1.Apple a) -> a.getWeight() < 80 ||

"brown".equals(a.getColor()));

System.out.println(weirdApples);

}

public static List filterApples(List inventory, Predicate p) {

List 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 +

'}';

}

}

}

java8中内置filter函数

static Collection filter(Collection c, Predicate p);

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

filterApples(inventory, (Apple a) -> a.getWeight() > 150 );

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

filter(inventory, (Apple a) -> a.getWeight() > 150 );

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/541928.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

getlong_Java LocalDateTime类| 带示例的getLong()方法

getlongLocalDateTime类的getLong()方法 (LocalDateTime Class getLong() method) getLong() method is available in java.time package. getLong()方法在java.time包中可用。 getLong() method is used to get the value as long for the given temporal field from this dat…

java.io和util的区别_Java NIO与IO的区别和比较

Java NIO与IO的区别和比较导读J2SE1.4以上版本中发布了全新的I/O类库。本文将通过一些实例来简单介绍NIO库提供的一些新特性&#xff1a;非阻塞I/O&#xff0c;字符转换&#xff0c;缓冲以及通道。一. 介绍NIONIO包(java.nio.*)引入了四个关键的抽象数据类型&#xff0c;它们共…

Java LocalDate类| isSupported()方法与示例

LocalDate类isSupported()方法 (LocalDate Class isSupported() method) Syntax: 句法&#xff1a; public boolean isSupported (TemporalField t_field);public boolean isSupported (TemporalUnit t_unit);isSupported() method is available in java.time package. isSupp…

区块链+税务的思考

2016年&#xff0c;区块链技术火了&#xff01;各大金融公司、互联网巨头都竞相参加到区块链技术的研究中。我们公司的业务是税务的信息化领域&#xff0c;也希望通过区块链技术的应用&#xff0c;来提升为财税领域的服务。 区块链技术优缺点总结 下图是对区块链技术的一些特点…

java hasset 顺序_java集合排序问题

List: 元素是有序的&#xff0c;元素可以重复&#xff0c;因为该集合体系有索引(脚标)常用的子类对象&#xff1a;1————ArrayList 底层的数据结构是使用的数组结构特点&#xff1a;查询速度快&#xff0c;但是增删比较慢2————LinkedList底层的数据结构使用的是链表结构…

如何使用JavaScript删除CSS属性?

In this article, well see how we can remove a CSS property from a certain element using JavaScript? We can remove only those properties that we assign ourselves and the pre-default ones cannot be removed by this method. 在本文中&#xff0c;我们将看到如何使…

Django 缓存系统

Django 是动态网站&#xff0c;一般来说需要实时地生成访问的网页&#xff0c;展示给访问者&#xff0c;这样&#xff0c;内容可以随时变化&#xff0c;但是从数据库读多次把所需要的数据取出来&#xff0c;要比从内存或者硬盘等一次读出来 付出的成本大很多。 缓存系统工作原理…

java web截屏_java_WebDriver中实现对特定的Web区域截图方法,用过 WebDriver 的同学都知道,We - phpStudy...

WebDriver中实现对特定的Web区域截图方法用过 WebDriver 的同学都知道&#xff0c;WebDriver 可以对浏览器中的页面进行截图。例如&#xff1a;public byte[] takeScreenshot() throws IOException {TakesScreenshot takesScreenshot (TakesScreenshot) driver;return takesSc…

c语言 关键字const_C ++ const关键字| 查找输出程序| 套装1

c语言 关键字constProgram 1: 程序1&#xff1a; #include <iostream>using namespace std;void fun(int& A) const{A 10;}int main(){int X 0;fun(X);cout << X;return 0;}Output: 输出&#xff1a; [Error] non-member function void fun(int) cannot ha…

【喜报】JEEWX荣获“2016 年度码云新增热门开源软件排行榜”第一名!

为什么80%的码农都做不了架构师&#xff1f;>>> 2016 年度码云新增项目排行榜 TOP 50 正式出炉&#xff01;根据 2016 年在码云上新增开源项目的 Watch、Star、Fork 数量以及其他角度的统计&#xff0c;JEEWX捷微管家荣获“2016 年度码云新增热门开源软件排行榜”第…

java 二叉树特点_疯狂java笔记之树和二叉树

树的概述树是一种非常常用的数据结构&#xff0c;树与前面介绍的线性表&#xff0c;栈&#xff0c;队列等线性结构不同&#xff0c;树是一种非线性结构1.树的定义和基本术语计算机世界里的树&#xff0c;是从自然界中实际的树抽象而来的&#xff0c;它指的是N个有父子关系的节点…

编辑距离 dp_使用动态编程(DP)编辑距离

编辑距离 dpProblem: You are given two strings s1 and s2 of length M and N respectively. You can perform following operations on the string. 问题&#xff1a;给您两个长度分别为M和N的字符串s1和s2 。 您可以对字符串执行以下操作。 Insert a character at any posi…

tomcat +apache 配置集群

2019独角兽企业重金招聘Python工程师标准>>> APACHE2.2.25TOMCAT6.0.37配置负载均衡 目标: 使用 apache 和 tomcat 配置一个可以应用的 web 网站&#xff0c;要达到以下要求&#xff1a; 1. Apache 做为 HttpServer &#xff0c;后面连接多个 tomcat 应用实例&…

java双缓存机制_详解JVM类加载机制及类缓存问题的处理方法

前言大家应该都知道&#xff0c;当一个Java项目启动的时候&#xff0c;JVM会找到main方法&#xff0c;根据对象之间的调用来对class文件和所引用的jar包中的class文件进行加载(其步骤分为加载、验证、准备、解析、初始化、使用和卸载)&#xff0c;方法区中开辟内存来存储类的运…

oracle中dbms_并发和由于DBMS中的并发导致的问题

oracle中dbms并发 (Concurrency) The ability of a database system which handles simultaneously or a number of transactions by interleaving parts of the actions or the overlapping this is called concurrency of the system. 数据库系统通过交织部分操作或重叠操作来…

什么是mvc?

什么是MVCMVC 是一种设计模式&#xff0c;它将应用划分为3 个部分&#xff1a;数据&#xff08;模型&#xff09;、展现层&#xff08;视图&#xff09;和用户交互层&#xff08;控制器&#xff09;。换句话说&#xff0c;一个事件的发生是这样的过程&#xff1a;1&#xff0e;…

mysql的安装和基本命令_MySQL安装以及简单命令用法

MYSQL:关系型数据库存储引擎:负责将逻辑层的概念转化为物理层机制&#xff0c;在物理层完成物理机制。支持事务&#xff1a;transaction必须满足的条件&#xff1a;ACID(一致性,持久性,原子性,隔离性)锁&#xff1a;并发访问随机访问&#xff1a;数据在磁盘上是随机存储的安装&…

将数组转换为JavaScript中的对象

Lets say you have the following array, 假设您有以下数组&#xff0c; const nums [1, 2, 3, 4, 5];console.log(nums);Output 输出量 (5) [1, 2, 3, 4, 5]We know that nums is an array and we can see in the output that we get an array. Lets convert it into an ob…

docker集群运行在calico网络上

2019独角兽企业重金招聘Python工程师标准>>> ##网络及版本信息 docker1 centos7 192.168.75.200 docker2 centos7 192.168.75.201 物理网络 192.168.75.1/24 Docker version 1.10.3, build 3999ccb-unsupported &#xff0c;安装过程略 # calicoctl version Version…