当前位置: 首页 > news >正文

JDK 8 函数式接口全集

JDK 8 函数式接口全集

  • 函数式接口如何定义
    • 关于注解 @FunctionalInterface
  • 函数式接口的分类与简单使用
    • 生产型接口 Supplier
      • 使用
    • 消费型接口 Consumer
      • 使用
    • ​​函数型接口(Function)​​
      • 实例(合并字符串)
    • ​​断言型接口(Predicate)​​
      • 示例
    • 操作型接口(Operator)​​
      • 示例

函数式接口如何定义

所谓的函数式接口,当然首先是一个接口,然后就是在这个接口里面只能有一个抽象方法

注意,在JDK8 以后,接口内,也支持 默认方法(default)和静态方法(static
所以,在一个函数式接口内是可能有多个方法的。

关于注解 @FunctionalInterface

在这里插入图片描述

错误案例(定义两个抽象方法)

    @FunctionalInterfacepublic interface CompareHandler {Integer theBigger(Integer i1, Integer i2);Integer theSmaller(Integer i1, Integer i2);}

直接报错

合法接口

	@FunctionalInterfacepublic interface CompareHandler {Integer theBigger(Integer i1, Integer i2);default Integer theSmaller(Integer i1, Integer i2){return i1>i2?i2:i1;}static Boolean compare100(Integer i1){return i1>100;}}

使用

        CompareHandler handler = (i3, i4)->{return i3>i4?i3:i4;};System.out.println(handler.theSmaller(1, 2));System.out.println(handler.theBigger(1,2));System.out.println(CompareHandler.compare100(1));//1//2//false

函数式接口的分类与简单使用

在 JDK 8 中,函数式接口(Functional Interface)是指仅包含一个抽象方法的接口,支持通过 Lambda 表达式或方法引用来实现。

方法引用: 不使用匿名函数,而是在类中直接定义一个 参数和返回值 与定义的函数式接口一致的的方法。
doBusiness(“wu”, this::methed1)
public static String doBusiness(String name , CompareHandler compareHandler){……}

java.util.function 包中预定义了丰富的函数式接口,按功能可分为以下几类:

生产型接口 Supplier

功能​​:无输入参数,返回一个结果。
​​核心接口​​:

  • ​​Supplier​​
    方法:T get()
    示例:延迟生成对象或值
@FunctionalInterface
public interface Supplier<T> {/*** Gets a result.** @return a result*/T get();
}

使用

Supplier<LocalDate> dateSupplier = () -> LocalDate.now();
System.out.println(dateSupplier.get()); // 当前日期

消费型接口 Consumer

功能​​:接收参数但不返回结果。

@FunctionalInterface
public interface Consumer<T> {/*** Performs this operation on the given argument.** @param t the input argument*/void accept(T t);/*** Returns a composed {@code Consumer} that performs, in sequence, this* operation followed by the {@code after} operation. If performing either* operation throws an exception, it is relayed to the caller of the* composed operation.  If performing this operation throws an exception,* the {@code after} operation will not be performed.** @param after the operation to perform after this operation* @return a composed {@code Consumer} that performs in sequence this* operation followed by the {@code after} operation* @throws NullPointerException if {@code after} is null*/default Consumer<T> andThen(Consumer<? super T> after) {Objects.requireNonNull(after);return (T t) -> { /*** 联系起来看:con1.andThen(con2).accept(name);* accept(t); 就是调用 con1 的 消费方法* after.accept(t); 就是调用 con2 的 消费方法*/accept(t); after.accept(t);};}
}

使用

import java.util.function.Consumer;public class ConsumerDemo {public static void main(String[] args) {operatorString("张三", (s) -> System.out.println(s));operatorString("张三", (s) -> System.out.println(s), (s)-> System.out.println(new StringBuilder(s).reverse().toString()));}//定义一个方法,消费一个字符串数据private static void operatorString(String name, Consumer<String> con) {con.accept(name);}//定义一个方法,用不同的方式消费同一个字符串两次private static void operatorString(String name, Consumer<String> con1,Consumer<String> con2) {
//        con1.accept(name);
//        con2.accept(name);//返回一个组合的Consumercon1.andThen(con2).accept(name);}
}

​​函数型接口(Function)​​

​​功能​​:接收一个参数,返回转换后的结果。

核心接口​​:

  • Function<T, R>
  • BiFunction<T, U, R>
@FunctionalInterface
public interface Function<T, R> {/*** Applies this function to the given argument.** @param t the function argument* @return the function result*/R apply(T t);/*** Returns a composed function that first applies the {@code before}* function to its input, and then applies this function to the result.* If evaluation of either function throws an exception, it is relayed to* the caller of the composed function.** @param <V> the type of input to the {@code before} function, and to the*           composed function* @param before the function to apply before this function is applied* @return a composed function that first applies the {@code before}* function and then applies this function* @throws NullPointerException if before is null** @see #andThen(Function)*/default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {Objects.requireNonNull(before);return (V v) -> apply(before.apply(v));}/*** Returns a composed function that first applies this function to* its input, and then applies the {@code after} function to the result.* If evaluation of either function throws an exception, it is relayed to* the caller of the composed function.** @param <V> the type of output of the {@code after} function, and of the*           composed function* @param after the function to apply after this function is applied* @return a composed function that first applies this function and then* applies the {@code after} function* @throws NullPointerException if after is null** @see #compose(Function)*/default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {Objects.requireNonNull(after);return (T t) -> after.apply(apply(t));}/*** Returns a function that always returns its input argument.** @param <T> the type of the input and output objects to the function* @return a function that always returns its input argument*/static <T> Function<T, T> identity() {return t -> t;}
}

实例(合并字符串)

BiFunction<String, String, String> concat = (s1, s2) -> s1 + s2;
System.out.println(concat.apply("Hello", "World")); // HelloWorld

​​断言型接口(Predicate)​​

​​功能​​:接收参数,返回布尔值。

方法介绍

  1. boolean test(T t):对给定的参数进行判断(判断逻辑由Lambda表达式实现),返回一个布尔值
  2. default Predicate< T > negate():返回一个逻辑的否定,对应逻辑非
  3. default Predicate< T > and():返回一个组合判断,对应短路与
  4. default Predicate< T > or():返回一个组合判断,对应短路或
  5. isEqual():测试两个参数是否相等
  6. Predicate< T >:接口通常用于判断参数是否满足指定的条件

/*** 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);}
}

示例

import java.util.function.Predicate;public class ConsumerTest {public static void main(String[] args) {boolean string = chenkString("张三", s -> s.equals("张三"));System.out.println(string);boolean hello = chenkString("hello", s -> s.length() > 8, s -> s.length() < 18);System.out.println(hello);}//判定给定的字符串是否满足要求
//    private static boolean chenkString(String s, Predicate<String> pre){
//        return pre.test(s);
//    }private static boolean chenkString(String s, Predicate<String> pre){return pre.negate().test(s);}//    private static boolean chenkString(String s, Predicate<String> pre, Predicate<String> pre1){
//        return pre.and(pre1).test(s);
//    }private static boolean chenkString(String s, Predicate<String> pre, Predicate<String> pre1){return pre.or(pre1).test(s);}
}

操作型接口(Operator)​​

​​功能​​:输入与输出类型相同,用于数据转换或计算。
核心接口​​:

  • UnaryOperator​​(继承 Function<T, T>)
    方法:T apply(T t)
  • BinaryOperator​​(继承 BiFunction<T, T, T>)
    方法:T apply(T t1, T t2)

示例

UnaryOperator<Integer> square = n -> n * n;
System.out.println(square.apply(3)); // 9BinaryOperator<Integer> sum = (a, b) -> a + b;
System.out.println(sum.apply(2, 3)); // 5
http://www.xdnf.cn/news/210871.html

相关文章:

  • Electron读取本地文件
  • 客户案例分享|运营商数智化经典案例 — XX运营商
  • TRAE历史版本下载参考
  • JavaScript性能优化实战:从基础到高级的全面指南
  • 精益数据分析(32/126):电商指标优化与搜索策略解析
  • 工业声纹采集设备的市场需求趋势简析
  • 好未来golang后端开发
  • iOS - 音频: Core Audio - 播放
  • 【阿里云大模型高级工程师ACP习题集】2.7 通过微调增强模型能力 (上篇)(⭐️⭐️⭐️ 重点章节!!!)
  • 【Luogu】动态规划七
  • 3D Gaussian Splatting部分原理介绍和CUDA代码解读
  • 实验六 文件操作实验
  • 计算机视觉与深度学习 | 双目立体匹配算法理论+Opencv实践+matlab实践
  • 20250429-李彦宏口中的MCP:AI时代的“万能接口“
  • hover加图层图放大
  • 多块盘创建RAID5以及后增加空间
  • shell(4)
  • UBUS 通信接口的使用——添加一个object对象(ubus call)
  • 开放平台架构方案- GraphQL 详细解释
  • 2025年- H13-Lc120-189.轮转数组(普通数组)---java版
  • Cliosoft安装
  • 【AI学习】李宏毅新课《DeepSeek-R1 这类大语言模型是如何进行「深度思考」(Reasoning)的?》的部分纪要
  • 大屏 UI 设计:解锁视觉盛宴的奥秘
  • Microsoft .NET Framework 3.5 离线安装包 下载
  • python celery框架结合django的使用
  • 爬虫学习笔记(五)---数据解析之re
  • 【最新 MCP 战神手册 09】利用资源和提示增强上下文
  • Linux批量管理:Ansible自动化运维指南
  • 飞蛾扑火算法优化+Transformer四模型回归打包(内含MFO-Transformer-LSTM及单独模型)
  • 开源Kotlin从零单排0基础完美入门教程