• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
思想人生从关注生活开始
博客园    首页    新随笔    联系   管理    订阅  订阅

java入门之Function<T, R>详解

一、源码分析
package java.util.function;

import java.util.Objects;

/**
* 表示接受一个参数并生成结果的函数。
*
* <p>这是一个<a href="package-summary.html">函数式接口</a>,其功能方法为{@link #apply(Object)}。
*
* @param <T> 函数输入的类型
* @param <R> 函数结果的类型
*
* @since 1.8
*/
@FunctionalInterface
public interface Function<T, R> {

/**
* 将此函数应用于给定的参数。
*
* @param t 函数参数
* @return 函数结果
*/
R apply(T t);

/**
* 返回一个组合函数,先将{@code before}函数应用于其输入,然后将此函数应用于结果。
* 如果任一函数的评估引发异常,则将其传递给组合函数的调用者。
*
* @param <V> {@code before}函数的输入类型,以及组合函数的输入类型
* @param before 在应用此函数之前应用的函数
* @return 先应用{@code before}函数,然后应用此函数的组合函数
* @throws NullPointerException 如果before为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));
}

/**
* 返回一个组合函数,先将此函数应用于其输入,然后将{@code after}函数应用于结果。
* 如果任一函数的评估引发异常,则将其传递给组合函数的调用者。
*
* @param <V> {@code after}函数的输出类型,以及组合函数的输出类型
* @param after 在应用此函数之后应用的函数
* @return 先应用此函数,然后应用{@code after}函数的组合函数
* @throws NullPointerException 如果after为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));
}

/**
* 返回一个始终返回其输入参数的函数。
*
* @param <T> 函数的输入和输出对象的类型
* @return 始终返回其输入参数的函数
*/
static <T> Function<T, T> identity() {
return t -> t;
}
}

二、应用用例讲解

接下来,让我们举几个例子说明`Function`接口的使用方式:

```java
import java.util.function.Function;

public class Main {
public static void main(String[] args) {
// Example 1: 使用compose方法组合两个函数
Function<Integer, String> intToString = Object::toString;
Function<String, String> quote = s -> "'" + s + "'";
Function<Integer, String> quoteIntToString = quote.compose(intToString);
System.out.println(quoteIntToString.apply(123)); // 输出:'123'

// Example 2: 使用andThen方法组合两个函数
Function<String, Integer> stringToInt = Integer::parseInt;
Function<String, Integer> lengthPlusOne = s -> s.length() + 1;
Function<String, Integer> stringLengthPlusOne = stringToInt.andThen(lengthPlusOne);
System.out.println(stringLengthPlusOne.apply("Hello")); // 输出:6

// Example 3: 使用identity方法
Function<String, String> identityFunction = Function.identity();
System.out.println(identityFunction.apply("Java")); // 输出:Java
}
}
```

这些例子展示了如何使用`Function`接口的`compose`、`andThen`方法以及`identity`方法来组合和创建函数。

posted @ 2024-02-23 14:14  JackYang  阅读(656)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3