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

相关文章

如何用java对接微信小程序下单后的发货接口

《如何用java对接微信小程序下单后的发货接口》:本文主要介绍在微信小程序后台实现发货通知的步骤,包括获取Access_token、使用RestTemplate调用发货接口、处理AccessTok... 目录配置参数 调用代码获取Access_token调用发货的接口类注意点总结配置参数 首先需要获取Ac

Java逻辑运算符之&&、|| 与&、 |的区别及应用

《Java逻辑运算符之&&、||与&、|的区别及应用》:本文主要介绍Java逻辑运算符之&&、||与&、|的区别及应用的相关资料,分别是&&、||与&、|,并探讨了它们在不同应用场景中... 目录前言一、基本概念与运算符介绍二、短路与与非短路与:&& 与 & 的区别1. &&:短路与(AND)2. &:非短

Java的volatile和sychronized底层实现原理解析

《Java的volatile和sychronized底层实现原理解析》文章详细介绍了Java中的synchronized和volatile关键字的底层实现原理,包括字节码层面、JVM层面的实现细节,以... 目录1. 概览2. Synchronized2.1 字节码层面2.2 JVM层面2.2.1 ente

讯飞webapi语音识别接口调用示例代码(python)

《讯飞webapi语音识别接口调用示例代码(python)》:本文主要介绍如何使用Python3调用讯飞WebAPI语音识别接口,重点解决了在处理语音识别结果时判断是否为最后一帧的问题,通过运行代... 目录前言一、环境二、引入库三、代码实例四、运行结果五、总结前言基于python3 讯飞webAPI语音

MyBatis-Plus中Service接口的lambdaUpdate用法及实例分析

《MyBatis-Plus中Service接口的lambdaUpdate用法及实例分析》本文将详细讲解MyBatis-Plus中的lambdaUpdate用法,并提供丰富的案例来帮助读者更好地理解和应... 目录深入探索MyBATis-Plus中Service接口的lambdaUpdate用法及示例案例背景

什么是 Java 的 CyclicBarrier(代码示例)

《什么是Java的CyclicBarrier(代码示例)》CyclicBarrier是多线程协同的利器,适合需要多次同步的场景,本文通过代码示例讲解什么是Java的CyclicBarrier,感... 你的回答(口语化,面试场景)面试官:什么是 Java 的 CyclicBarrier?你:好的,我来举个例

Java使用Mail构建邮件功能的完整指南

《Java使用Mail构建邮件功能的完整指南》JavaMailAPI是一个功能强大的工具,它可以帮助开发者轻松实现邮件的发送与接收功能,本文将介绍如何使用JavaMail发送和接收邮件,希望对大家有所... 目录1、简述2、主要特点3、发送样例3.1 发送纯文本邮件3.2 发送 html 邮件3.3 发送带

Java实现数据库图片上传功能详解

《Java实现数据库图片上传功能详解》这篇文章主要为大家详细介绍了如何使用Java实现数据库图片上传功能,包含从数据库拿图片传递前端渲染,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1、前言2、数据库搭建&nbsChina编程p; 3、后端实现将图片存储进数据库4、后端实现从数据库取出图片给前端5、前端拿到

Java实现将byte[]转换为File对象

《Java实现将byte[]转换为File对象》这篇文章将通过一个简单的例子为大家演示Java如何实现byte[]转换为File对象,并将其上传到外部服务器,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言1. 问题背景2. 环境准备3. 实现步骤3.1 从 URL 获取图片字节数据3.2 将字节数组

Java捕获ThreadPoolExecutor内部线程异常的四种方法

《Java捕获ThreadPoolExecutor内部线程异常的四种方法》这篇文章主要为大家详细介绍了Java捕获ThreadPoolExecutor内部线程异常的四种方法,文中的示例代码讲解详细,感... 目录方案 1方案 2方案 3方案 4结论方案 1使用 execute + try-catch 记录