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

相关文章

Spring IOC的三种实现方式详解

《SpringIOC的三种实现方式详解》:本文主要介绍SpringIOC的三种实现方式,在Spring框架中,IOC通过依赖注入来实现,而依赖注入主要有三种实现方式,构造器注入、Setter注入... 目录1. 构造器注入(Cons编程tructor Injection)2. Setter注入(Setter

Java function函数式接口的使用方法与实例

《Javafunction函数式接口的使用方法与实例》:本文主要介绍Javafunction函数式接口的使用方法与实例,函数式接口如一支未完成的诗篇,用Lambda表达式作韵脚,将代码的机械美感... 目录引言-当代码遇见诗性一、函数式接口的生物学解构1.1 函数式接口的基因密码1.2 六大核心接口的形态学

Spring IOC控制反转的实现解析

《SpringIOC控制反转的实现解析》:本文主要介绍SpringIOC控制反转的实现,IOC是Spring的核心思想之一,它通过将对象的创建、依赖注入和生命周期管理交给容器来实现解耦,使开发者... 目录1. IOC的基本概念1.1 什么是IOC1.2 IOC与DI的关系2. IOC的设计目标3. IOC

Python实现文件下载、Cookie以及重定向的方法代码

《Python实现文件下载、Cookie以及重定向的方法代码》本文主要介绍了如何使用Python的requests模块进行网络请求操作,涵盖了从文件下载、Cookie处理到重定向与历史请求等多个方面,... 目录前言一、下载网络文件(一)基本步骤(二)分段下载大文件(三)常见问题二、requests模块处理

Spring Boot统一异常拦截实践指南(最新推荐)

《SpringBoot统一异常拦截实践指南(最新推荐)》本文介绍了SpringBoot中统一异常处理的重要性及实现方案,包括使用`@ControllerAdvice`和`@ExceptionHand... 目录Spring Boot统一异常拦截实践指南一、为什么需要统一异常处理二、核心实现方案1. 基础组件

java中的HashSet与 == 和 equals的区别示例解析

《java中的HashSet与==和equals的区别示例解析》HashSet是Java中基于哈希表实现的集合类,特点包括:元素唯一、无序和可包含null,本文给大家介绍java中的HashSe... 目录什么是HashSetHashSet 的主要特点是HashSet 的常用方法hasSet存储为啥是无序的

IDEA运行spring项目时,控制台未出现的解决方案

《IDEA运行spring项目时,控制台未出现的解决方案》文章总结了在使用IDEA运行代码时,控制台未出现的问题和解决方案,问题可能是由于点击图标或重启IDEA后控制台仍未显示,解决方案提供了解决方法... 目录问题分析解决方案总结问题js使用IDEA,点击运行按钮,运行结束,但控制台未出现http://

解决Spring运行时报错:Consider defining a bean of type ‘xxx.xxx.xxx.Xxx‘ in your configuration

《解决Spring运行时报错:Considerdefiningabeanoftype‘xxx.xxx.xxx.Xxx‘inyourconfiguration》该文章主要讲述了在使用S... 目录问题分析解决方案总结问题Description:Parameter 0 of constructor in x

解决IDEA使用springBoot创建项目,lombok标注实体类后编译无报错,但是运行时报错问题

《解决IDEA使用springBoot创建项目,lombok标注实体类后编译无报错,但是运行时报错问题》文章详细描述了在使用lombok的@Data注解标注实体类时遇到编译无误但运行时报错的问题,分析... 目录问题分析问题解决方案步骤一步骤二步骤三总结问题使用lombok注解@Data标注实体类,编译时

JSON字符串转成java的Map对象详细步骤

《JSON字符串转成java的Map对象详细步骤》:本文主要介绍如何将JSON字符串转换为Java对象的步骤,包括定义Element类、使用Jackson库解析JSON和添加依赖,文中通过代码介绍... 目录步骤 1: 定义 Element 类步骤 2: 使用 Jackson 库解析 jsON步骤 3: 添