Function和BiFunction详解

本文深入探讨了Java中Function和BiFunction接口的定义与使用,包括它们的方法如apply、compose和andThen,以及如何通过Lambda表达式实现这些功能。同时,提供了具体的代码示例,展示了如何使用Function和BiFunction处理数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Function和BiFunction详解

Function

jdk源码Function的定义:

//类型T入参,类型R是返回值的类型
@FunctionalInterface
public interface Function<T, R> {

    /**
        接受一个参数,返回一个结果
     */
    R apply(T t);

    /**
     * 默认方法是讲的课8新加入的一种类型,入参before是一个Function(接受参数V类型,输出T类型),从实现来看其首先调用before的行为得到输出T,
     * 随后T作为当前Function的入参,最后当前Function输入R类型。即:compose函数传入的函数首先被调用,得到的结果作为当前Function的入参使用
     */
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }

    /**
     * andThen是和compose相反的操作,当前Function首先被调用,得到的结果作为参数after的入参,调用after。
     */
    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }

    /**
     * 对接受的元素,不做处理
     */
    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

Function例子:

package com.fjh.jvm;

import java.util.function.Function;

public class FunctionTest {

    public static void main(String[] args) {
        FunctionTest test = new FunctionTest();
        System.out.println(test.compute(1,a -> a+1));

       // 普通定义
        Function<Integer,Integer> function = new Function<Integer,Integer>() {
            @Override
            public Integer apply(Integer o) {
                return o * o;
            }
        };
        Function<Integer, String> function1 = function.andThen(new Function<Integer, String>() {
            @Override
            public String apply(Integer integer) {
                return "result is " + integer;
            }
        });

        String apply = function1.apply(2);
        System.out.println(apply);
        // 用lambda的方式实现
        Function<Integer,Integer> lambdaFunc = o -> o*o;
        Function<Integer, String> function2 = lambdaFunc.andThen(o -> "result is " + o);
        String apply1 = function2.apply(2);
        System.out.println(apply1);

    }
    public int compute(int a, Function<Integer,Integer> function){
        return function.apply(a);
    }

}

BiFunction

jdk源码

package java.util.function;

import java.util.Objects;

/**表示一个方法它接受两个参数返回一个结果
 * Represents a function that accepts two arguments and produces a result.
 * This is the two-arity specialization of {@link Function}.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #apply(Object, Object)}.
 *
 * @param <T> the type of the first argument to the function
 * @param <U> the type of the second argument to the function
 * @param <R> the type of the result of the function
 *
 * @see Function
 * @since 1.8
 */
@FunctionalInterface
public interface BiFunction<T, U, R> {

    /**
     * Applies this function to the given arguments.
     *
     * @param t the first function argument
     * @param u the second function argument
     * @return the function result
     */
    R apply(T t, U u);

    /**
     * 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
     */
    default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t, U u) -> after.apply(apply(t, u));
    }
}

例子 :输入两个int值,输出他们的和

 //BiFunction
BiFunction<Integer,Integer,Integer> biFunction = (x,y) -> x+y;
Integer apply2 = biFunction.apply(1, 2);
System.out.println(apply2);

Lambda处理List以及BiFunction处理List

package com.fjh.jvm;

import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import java.util.stream.Collectors;

public class FunctionTest2 {
    public static void main(String[] args) {
        Person zhangsan = new Person(20,"zhangsan");
        Person lisi = new Person(30,"lisi");
        Person wangwu = new Person(40,"wangwu");

        List<Person> personList = new ArrayList<>();
        personList.add(zhangsan);
        personList.add(lisi);
        personList.add(wangwu);

        FunctionTest2 test2 = new FunctionTest2();
        List<Person> zhangsan1 = test2.getPersonByName("zhangsan", personList);
        List<Person> personByAge = test2.getPersonByAge(20, personList);
        System.out.println(zhangsan1);
        System.out.println(personByAge);
        
        List<Person> personByAge2 = test2.getPersonByAge2(20, personList, (age, list) -> list.stream()
                .filter(p -> p.getAge() > age).collect(Collectors.toList()));
        System.out.println(personByAge2);


    }

    public List<Person> getPersonByName(String name,List<Person> personList){
        return personList.stream().filter(person -> person.getName().equals(name)).collect(Collectors.toList());
    }

    public List<Person> getPersonByAge(int age,List<Person> personList){
        BiFunction<Integer,List<Person>,List<Person>> biFunction
                = (ageOfPerson,persons) -> persons.stream()
                .filter(person -> person.getAge() > 20)
                .collect(Collectors.toList());
        return biFunction.apply(age,personList);
    }
    // 更加灵活的方式 让调用者实现过滤的条件 是大于还是小于
    public List<Person> getPersonByAge2(int age,List<Person> personList,BiFunction<Integer,List<Person>,List<Person>> biFunction){
        return biFunction.apply(age,personList);
    }
}

<think>我们正在讨论Java中的Function接口。FunctionJava 8引入的一个函数式接口,位于java.util.function包中。它代表一个接受一个参数并产生结果的函数。其抽象方法为R apply(T t),即接受类型为T的参数,返回类型为R的结果。 除了apply方法,Function接口还有两个默认方法: 1. compose(Function before):返回一个组合函数,先执行before函数,再执行当前函数。 2. andThen(Function after):返回一个组合函数,先执行当前函数,再执行after函数。 另外,还有一个静态方法identity(),返回一个始终返回其输入参数的函数。 下面我们将通过示例来详细说明这些方法的使用。 示例1:基本使用 定义一个将字符串转换为长度的函数。</think>### Java `Function` 接口详解与使用指南 `Function<T, R>` 是 Java 8 引入的核心函数式接口,用于表示**接受一个输入参数并返回结果的函数**。其定义如下: ```java @FunctionalInterface public interface Function<T, R> { R apply(T t); // 核心方法:接收T类型参数,返回R类型结果 // 组合函数 default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {...} default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {...} // 返回自身函数 static <T> Function<T, T> identity() { return t -> t; } } ``` #### 核心方法解析 1. **`apply(T t)`** 函数的核心执行逻辑: ```java Function<String, Integer> strToLength = s -> s.length(); System.out.println(strToLength.apply("Hello")); // 输出: 5 ``` 2. **`compose()`** 组合函数(先执行参数函数,再执行当前函数): ```java Function<Integer, String> intToHex = i -> "0x" + Integer.toHexString(i); Function<String, Integer> strToInt = s -> Integer.parseInt(s); Function<String, String> hexConverter = intToHex.compose(strToInt); System.out.println(hexConverter.apply("255")); // 输出: 0xff ``` 3. **`andThen()`** 链式调用(先执行当前函数,再执行参数函数): ```java Function<String, String> toUpper = s -> s.toUpperCase(); Function<String, String> addExclamation = s -> s + "!"; Function<String, String> shout = toUpper.andThen(addExclamation); System.out.println(shout.apply("hello")); // 输出: HELLO! ``` 4. **`identity()`** 返回输入值本身的函数: ```java Function<String, String> sameString = Function.identity(); System.out.println(sameString.apply("Test")); // 输出: Test ``` #### 实际应用场景 1. **集合转换** ```java List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); // 将名字列表转换为长度列表 List<Integer> lengths = names.stream() .map(s -> s.length()) // 等价于 Function::apply .collect(Collectors.toList()); // [5, 3, 7] ``` 2. **条件处理管道** ```java Function<String, String> removeSpaces = s -> s.replace(" ", ""); Function<String, String> reverse = s -> new StringBuilder(s).reverse().toString(); Function<String, String> pipeline = removeSpaces.andThen(reverse); System.out.println(pipeline.apply("a b c")); // 输出: cba ``` 3. **工厂模式实现** ```java Map<String, Function<String, Shape>> shapeFactories = new HashMap<>(); shapeFactories.put("circle", radius -> new Circle(Double.parseDouble(radius))); shapeFactories.put("square", side -> new Square(Double.parseDouble(side))); Shape circle = shapeFactories.get("circle").apply("5.0"); ``` #### 与其他函数式接口配合 | 接口 | 输入参数 | 返回值 | 典型应用 | |---------------------|----------|--------|------------------------| | `Function<T,R>` | 1个(T) | R | 类型转换 | | `Consumer<T>` | 1个(T) | void | 遍历操作 | | `Supplier<T>` | 0个 | T | 延迟初始化 | | `Predicate<T>` | 1个(T) | boolean| 条件过滤 | | `BiFunction<T,U,R>` | 2个(T,U) | R | 合并操作(如字符串拼接)| ```java // 组合使用示例 Predicate<String> isLong = s -> s.length() > 3; Function<String, Integer> parseToInt = Integer::parseInt; Consumer<Integer> printer = System.out::println; Stream.of("123", "4567", "89") .filter(isLong) // 过滤长度>3的字符串 .map(parseToInt) // 转换为整数 .forEach(printer); // 打印结果 → 输出: 4567 ``` #### 最佳实践 1. **方法引用优先** 当逻辑已有现成方法时: ```java // 代替 s -> s.toUpperCase() Function<String, String> upper = String::toUpperCase; ``` 2. **避免副作用** 保持函数纯净(无状态修改): ```java // 不推荐(修改外部状态) List<String> result = new ArrayList<>(); Function<String, String> badExample = s -> { result.add(s); // 副作用! return s.toUpperCase(); }; ``` 3. **异常处理** 使用包装类处理受检异常: ```java Function<String, Integer> safeParse = s -> { try { return Integer.parseInt(s); } catch (NumberFormatException e) { return 0; // 默认值 } }; ``` > 通过 `Function` 接口,Java 实现了将函数作为一等公民处理的能力,显著提升了代码的灵活性表现力[^1][^2]。 --- ### 相关问题 1. `Function` 接口与 `UnaryOperator` 有什么区别联系? 2. 如何在 `Function` 组合链中实现异常传播机制? 3. 使用 `Function` 接口会带来哪些性能影响?如何优化? 4. 在哪些场景下应该优先选择 `BiFunction` 而不是 `Function`?
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值