Java 8 in action代码总结 1 - filter、Predicate接口

2024-01-23 22:32

本文主要是介绍Java 8 in action代码总结 1 - filter、Predicate接口,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 调用filter方法过滤目标集合
  • 自定义的Predicate接口 和 filter方法
    • JDK8自带的Predicate(谓词)接口

调用filter方法过滤目标集合

//调用filter的代码
//filter方法中ApplePredicate接口当作参数传入,
//在调用filter方法的时候则需要传入这个接口的具体实现,对应接口内的方法也要重写;具体的过滤也在filter重写方法的内部实现
List<Apple> apples = filter(inventory, new ApplePredicate() {@Overridepublic boolean test(Apple a) {return a.getWeight() > 119;}
});
System.out.println(apples);

自定义的Predicate接口 和 filter方法

  • 自定义Predicate接口的抽象方法的参数为最后具体要过滤和比较的对象
  • filter方法的参数是Predicate接口,以及需要过滤的集合或者数组
public static List<Apple> filter(List<Apple> inventory, ApplePredicate p){List<Apple> result = new ArrayList<>();for(Apple apple : inventory){if(p.test(apple)){result.add(apple);}}return result;
}   interface ApplePredicate{public boolean test(Apple a);
}   

总结:这边接口作为参数,是行为参数化的体现,是java8 in action中chapter 2的主题 - Passing code with behavior parameterization

JDK8自带的Predicate(谓词)接口

jdk8自带的Predicate接口,用来代替上面的自定义的谓词接口。
该接口中定义了test,negate,or ,and,isEqual等方法。
当调用这个接口的时候,我们需要先定义一个filter()方法,传入Collection操作对象,根据所要做的操作,传入适当个数的Predicate作为参数。

调用代码

List<Apple> greenApples = filterApples(inventory, FilteringApples::isGreenApple);
System.out.println(greenApples);List<Apple> greenApples2 = filterApples(inventory, (Apple a) -> "green".equals(a.getColor()));
System.out.println(greenApples2);

自定义filter方法

public static boolean isGreenApple(Apple apple) {return "green".equals(apple.getColor()); 
}public static List<Apple> filterApples(List<Apple> inventory, Predicate<Apple> p){List<Apple> result = new ArrayList<>();for(Apple apple : inventory){//取反Predicate<Apple> negate = p.negate();//取反静态方法Predicate<Apple> not = Predicate.not(p);if(negate.test(apple)){result.add(apple);}}return result;
}public static List<Apple> filterApples(List<Apple> inventory, Predicate<Apple> p,Predicate<Apple> p1){List<Apple> result = new ArrayList<>();for(Apple apple : inventory){//二合一Predicate<Apple> and = p.and(p1);//二选一Predicate<Apple> or = p.or(p1);if(and.test(apple)){result.add(apple);}}return result;
}

Predicate接口代码

package java.util.function;
import java.util.Objects;/*** Represents a predicate (boolean-valued function) of one argument.** <p>This is a <a href="package-summary.html">functional interface</a>* whose functional method is {@link #test(Object)}.** @param <T> the type of the input to the predicate** @since 1.8*/
@FunctionalInterface
public interface Predicate<T> {/*** Evaluates this predicate on the given argument.* 根据给定参数评估此谓词。** @param t the input argument* @return {@code true} if the input argument matches the predicate,* otherwise {@code false}*/boolean test(T t);/*** Returns a composed predicate that represents a short-circuiting logical* AND of this predicate and another.  When evaluating the composed* predicate, if this predicate is {@code false}, then the {@code other}* predicate is not evaluated.* 返回合并两个谓词逻辑的新的谓词** <p>Any exceptions thrown during evaluation of either predicate are relayed* to the caller; if evaluation of this predicate throws an exception, the* {@code other} predicate will not be evaluated.** @param other a predicate that will be logically-ANDed with this*              predicate* @return a composed predicate that represents the short-circuiting logical* AND of this predicate and the {@code other} predicate* @throws NullPointerException if other is null*/default Predicate<T> and(Predicate<? super T> other) {Objects.requireNonNull(other);return (t) -> test(t) && other.test(t);}/*** Returns a predicate that represents the logical negation of this* predicate.* 返回一个与给定代码逻辑相反的谓词,取反** @return a predicate that represents the logical negation of this* predicate*/default Predicate<T> negate() {return (t) -> !test(t);}/*** Returns a composed predicate that represents a short-circuiting logical* OR of this predicate and another.  When evaluating the composed* predicate, if this predicate is {@code true}, then the {@code other}* predicate is not evaluated.* 返回一个符合两个中的一个谓词的新的谓词** <p>Any exceptions thrown during evaluation of either predicate are relayed* to the caller; if evaluation of this predicate throws an exception, the* {@code other} predicate will not be evaluated.** @param other a predicate that will be logically-ORed with this*              predicate* @return a composed predicate that represents the short-circuiting logical* OR of this predicate and the {@code other} predicate* @throws NullPointerException if other is null*/default Predicate<T> or(Predicate<? super T> other) {Objects.requireNonNull(other);return (t) -> test(t) || other.test(t);}/*** Returns a predicate that tests if two arguments are equal according* to {@link Objects#equals(Object, Object)}.* 判断两个谓词的效果是否一样** @param <T> the type of arguments to the predicate* @param targetRef the object reference with which to compare for equality,*               which may be {@code null}* @return a predicate that tests if two arguments are equal according* to {@link Objects#equals(Object, Object)}*/static <T> Predicate<T> isEqual(Object targetRef) {return (null == targetRef)? Objects::isNull: object -> targetRef.equals(object);}/*** Returns a predicate that is the negation of the supplied predicate.* This is accomplished by returning result of the calling* 静态方法,和negate效果一样* {@code target.negate()}.** @param <T>     the type of arguments to the specified predicate* @param target  predicate to negate** @return a predicate that negates the results of the supplied*         predicate** @throws NullPointerException if target is null** @since 11*/@SuppressWarnings("unchecked")static <T> Predicate<T> not(Predicate<? super T> target) {Objects.requireNonNull(target);return (Predicate<T>)target.negate();}
}

总结:需要自定义的两段代码逻辑

  • 一是调用谓词的filter方法
    在这里插入图片描述

  • 二是谓词部分传入的代码片段或者方法
    在这里插入图片描述

这篇关于Java 8 in action代码总结 1 - filter、Predicate接口的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/637728

相关文章

SpringBoot条件注解核心作用与使用场景详解

《SpringBoot条件注解核心作用与使用场景详解》SpringBoot的条件注解为开发者提供了强大的动态配置能力,理解其原理和适用场景是构建灵活、可扩展应用的关键,本文将系统梳理所有常用的条件注... 目录引言一、条件注解的核心机制二、SpringBoot内置条件注解详解1、@ConditionalOn

通过Spring层面进行事务回滚的实现

《通过Spring层面进行事务回滚的实现》本文主要介绍了通过Spring层面进行事务回滚的实现,包括声明式事务和编程式事务,具有一定的参考价值,感兴趣的可以了解一下... 目录声明式事务回滚:1. 基础注解配置2. 指定回滚异常类型3. ​不回滚特殊场景编程式事务回滚:1. ​使用 TransactionT

使用Python实现全能手机虚拟键盘的示例代码

《使用Python实现全能手机虚拟键盘的示例代码》在数字化办公时代,你是否遇到过这样的场景:会议室投影电脑突然键盘失灵、躺在沙发上想远程控制书房电脑、或者需要给长辈远程协助操作?今天我要分享的Pyth... 目录一、项目概述:不止于键盘的远程控制方案1.1 创新价值1.2 技术栈全景二、需求实现步骤一、需求

Spring LDAP目录服务的使用示例

《SpringLDAP目录服务的使用示例》本文主要介绍了SpringLDAP目录服务的使用示例... 目录引言一、Spring LDAP基础二、LdapTemplate详解三、LDAP对象映射四、基本LDAP操作4.1 查询操作4.2 添加操作4.3 修改操作4.4 删除操作五、认证与授权六、高级特性与最佳

Spring Shell 命令行实现交互式Shell应用开发

《SpringShell命令行实现交互式Shell应用开发》本文主要介绍了SpringShell命令行实现交互式Shell应用开发,能够帮助开发者快速构建功能丰富的命令行应用程序,具有一定的参考价... 目录引言一、Spring Shell概述二、创建命令类三、命令参数处理四、命令分组与帮助系统五、自定义S

SpringSecurity JWT基于令牌的无状态认证实现

《SpringSecurityJWT基于令牌的无状态认证实现》SpringSecurity中实现基于JWT的无状态认证是一种常见的做法,本文就来介绍一下SpringSecurityJWT基于令牌的无... 目录引言一、JWT基本原理与结构二、Spring Security JWT依赖配置三、JWT令牌生成与

Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码

《Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码》:本文主要介绍Java中日期时间转换的多种方法,包括将Date转换为LocalD... 目录一、Date转LocalDateTime二、Date转LocalDate三、LocalDateTim

如何配置Spring Boot中的Jackson序列化

《如何配置SpringBoot中的Jackson序列化》在开发基于SpringBoot的应用程序时,Jackson是默认的JSON序列化和反序列化工具,本文将详细介绍如何在SpringBoot中配置... 目录配置Spring Boot中的Jackson序列化1. 为什么需要自定义Jackson配置?2.

Java中使用Hutool进行AES加密解密的方法举例

《Java中使用Hutool进行AES加密解密的方法举例》AES是一种对称加密,所谓对称加密就是加密与解密使用的秘钥是一个,下面:本文主要介绍Java中使用Hutool进行AES加密解密的相关资料... 目录前言一、Hutool简介与引入1.1 Hutool简介1.2 引入Hutool二、AES加密解密基础

Spring Boot项目部署命令java -jar的各种参数及作用详解

《SpringBoot项目部署命令java-jar的各种参数及作用详解》:本文主要介绍SpringBoot项目部署命令java-jar的各种参数及作用的相关资料,包括设置内存大小、垃圾回收... 目录前言一、基础命令结构二、常见的 Java 命令参数1. 设置内存大小2. 配置垃圾回收器3. 配置线程栈大小