Java 8 函数式接口:简化代码,提升表达力

在 Java 8 中,函数式接口是一个关键的特性,它们允许将方法作为参数传递或返回类型,从而提高代码的模块性和灵活性。下面是一些常见的函数式接口的实例代码。

1. Consumer<T>

Consumer<T> 接口代表一个接受单个输入参数且不返回结果的操作。它常用于对对象执行操作。

java 复制代码
import java.util.function.Consumer;

Consumer<String> printConsumer = System.out::println;
printConsumer.accept("Hello, World!");

2. Supplier<T>

Supplier<T> 接口提供一个没有参数的方法并返回一个泛型类型的结果。它通常用于延迟计算或构造。

java 复制代码
import java.util.function.Supplier;

Supplier<Double> randomSupplier = Math::random;
System.out.println(randomSupplier.get());

3. Function<T,R>

Function<T,R> 接口表示接受一个参数并产生结果的函数。这是一个非常通用的接口。

java 复制代码
import java.util.function.Function;

Function<String, Integer> lengthFunction = String::length;
System.out.println(lengthFunction.apply("Hello"));

4. Predicate<T>

Predicate<T> 接口表示一个参数的布尔值函数。

java 复制代码
import java.util.function.Predicate;

Predicate<String> nonEmptyStringPredicate = (String s) -> !s.isEmpty();
System.out.println(nonEmptyStringPredicate.test("Test"));

5.使用 Function<T,R> 进行函数组合

java 复制代码
Function<Integer, Integer> times2 = e -> e * 2;
Function<Integer, Integer> squared = e -> e * e;

Function<Integer, Integer> times2AndSquare = times2.andThen(squared);
System.out.println(times2AndSquare.apply(4)); // 输出 64

6.使用 Predicate<T> 进行逻辑组合

java 复制代码
Predicate<Integer> isEven = x -> x % 2 == 0;
Predicate<Integer> isPositive = x -> x > 0;

Predicate<Integer> isEvenAndPositive = isEven.and(isPositive);
System.out.println(isEvenAndPositive.test(4)); // true

7. UnaryOperator<T>

UnaryOperator<T> 是 Function<T, T> 的一个特例,用于操作单个操作数,其类型与结果类型相同。

java 复制代码
import java.util.function.UnaryOperator;

UnaryOperator<Integer> square = x -> x * x;
System.out.println(square.apply(5)); // 输出 25

8. BiFunction<T, U, R>

BiFunction<T, U, R> 接口表示接受两个参数并产生结果的函数。

java 复制代码
import java.util.function.BiFunction;

BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
System.out.println(add.apply(2, 3)); // 输出 5

9. BinaryOperator<T>

BinaryOperator<T> 是 BiFunction<T, T, T> 的一个特例,用于操作两个相同类型的操作数并返回相同类型的结果。

java 复制代码
import java.util.function.BinaryOperator;

BinaryOperator<Integer> multiply = (a, b) -> a * b;
System.out.println(multiply.apply(3, 4)); // 输出 12

10.使用 Function<T, R> 创建工厂方法

java 复制代码
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

class ComplexClass {
    private int value;

    ComplexClass(int value) {
        this.value = value;
    }

    // Getter and other methods...
}

Function<Integer, ComplexClass> complexClassFactory = ComplexClass::new;
ComplexClass complexInstance = complexClassFactory.apply(10);

11.UnaryOperator<T> 创建连续操作

java 复制代码
UnaryOperator<String> toUpperCase = String::toUpperCase;
UnaryOperator<String> addExclamation = str -> str + "!";

UnaryOperator<String> shout = toUpperCase.andThen(addExclamation);
System.out.println(shout.apply("hello")); // 输出 "HELLO!"

12. BiConsumer<T, U>

BiConsumer<T, U> 接口表示接受两个输入参数的操作,并且不返回任何结果。

java 复制代码
import java.util.function.BiConsumer;

BiConsumer<String, String> concatAndPrint = (a, b) -> System.out.println(a + b);
concatAndPrint.accept("Hello, ", "World!"); // 输出 Hello, World!

13. BiPredicate<T, U>

BiPredicate<T, U> 接口表示接受两个参数的布尔值函数。

java 复制代码
import java.util.function.BiPredicate;

BiPredicate<Integer, String> validate = (i, s) -> i > 0 && s.startsWith("A");
System.out.println(validate.test(1, "Apple")); // 输出 true

14. ToIntFunction<T>

ToIntFunction<T> 接口表示将一个对象转换为一个原始 int 类型的函数。

java 复制代码
import java.util.function.ToIntFunction;

ToIntFunction<String> length = String::length;
System.out.println(length.applyAsInt("Hello")); // 输出 5

通过这些特性,Java 8 的函数式接口极大地提升了代码的简洁性和可读性,同时也促进了函数式编程范式在 Java 社区中的普及。

相关推荐
wuminyu5 小时前
JVM规范学习总结:解释器与JIT编译器如何处理JVM字节码
java·linux·c语言·jvm·c++
txxzjmzlh5 小时前
SpringBoot 配置⽂件
java·spring boot·spring
当下新鲜事5 小时前
面向印刷包装设备的运动控制方案架构:E530标准型伺服系统与AC500 PLC的分层设计与选型实施
架构
Wang's Blog5 小时前
Java 项目实战: 交友项目 - 搜索附近的功能概述和分析
java·开发语言·交友
海宇AI5 小时前
零信任架构实战:基于海宇个人风险报告构建自动化分期商城信用额度初审网关
运维·人工智能·架构·自动化
骑着蜗牛撵大象3276 小时前
大模型 Agent 的沙箱护栏:gVisor 隔离、出口白名单与审计闭环
java·开发语言·jvm·安全·agent沙箱·gvisor·microvm
独泪了无痕6 小时前
Hutool之LocalDateTimeUtil:让时间间隔操作如虎添翼
java
AUTOSAR组织6 小时前
AUTOSAR架构下信息安全的实现方案
架构·汽车·autosar·软件架构·培训
三无少女指南7 小时前
从这里开始:Java 后端与 AI 工程的三条阅读路线
java·学习路线·ai工程
涛声依旧-底层原理研究所7 小时前
拆解 Cordis 底座:Agent 是如何被「组合」出来的
人工智能·架构