Java中的BiFunction

本文深入介绍了Java中的BiFunction接口,包括其基本概念、使用方法及常见应用场景。文章通过多个示例详细展示了如何利用BiFunction进行数据处理,并结合构造函数及addThen方法实现更复杂的业务逻辑。

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

介绍

BiFunction是一个函数式接口,表示一个接受两个输入值并返回一个输入值的运算符

@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));
    }
}
package cn.caigen.bifunctiontutorial;

import java.util.function.BiFunction;

public class BiFunctionEx1 {
    public static void main(String[] args) {
        BiFunction<String, String, String> biFunction = (firstName, lastName) -> firstName + " " + lastName;

        String fullName = biFunction.apply("Bill","John");
        System.out.println(fullName);
    }
}
//Map中的值进行修改
package cn.caigen.bifunctiontutorial;

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;

public class BiFunctionEx2 {
    public static void main(String[] args) {
        BiFunction<String, Integer, Integer> biFunction = BiFunctionEx2::getNewPrice;

        Map<String, Integer> localSalary = new HashMap<>();
        localSalary.put("hefei", 100);
        localSalary.put("nanjing", 20);
        localSalary.put("shanghai", 60);

        System.out.println("Origin salary: " + localSalary);
        localSalary.replaceAll(biFunction);
        System.out.println("After salary: " + localSalary);

    }

    public static int getNewPrice(String name, int salary) {
        if (name.equals("hefei")) {
            return salary * 10;
        }
        return salary;
    }
}

addThen(after)

addThen(after)方法首先返回一个组合的BiFunction。首先,调用BiFunction.apply将(T,U)转换成R。然后调用after.apply()将R变成V。若在此过程有一个发生错误,则将错误传给调用者。

通俗解释

@FunctionalInterface
public interface BiFunction<T, U, R> {
    // (T,U) -> R
    R apply(T t, U u);

    // (T,U) -> V
    default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        
        BiFunction<T, U, V> ret = (T t, U u) -> {
            // (T,U) -> R
            R r = this.apply(t, u);    
            
            // R -> V
            V v = after.apply(r);
            return v;
        };
        return ret;
    }
}
// 示例
package cn.caigen.bifunctiontutorial;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Function;

public class BiFunction_addThen_Ex3 {
    public static void main(String[] args) {
        BiFunction<String, Integer, String> biFunction =
                (local, salary) -> local + " 11";
        Function<String, String> biFunction1 =
                (local) -> local.toUpperCase();

        Map<String, Integer> localSalary = new HashMap<>();

        localSalary.put("beijing", 1000);
        localSalary.put("shanghai", 200);
        localSalary.put("tokyo", 50);
        
        System.out.println(localSalary);

        String result  = biFunction.andThen(biFunction1).apply("Bill", 123);
        System.out.println(result);
    }
}

BiFunction + 构造函数

通过className::new调用,返回对象。

package cn.caigen.bifunctiontutorial;

import java.util.function.BiFunction;

public class BiFunctionEx4 {
    public static void main(String[] args) {
        BiFunction<String, Integer, Staff> biFunction = Staff::new;

        Staff tom = biFunction.apply("Tom", 1000);
        Staff bill = biFunction.apply("Bill", 2000);

        tom.showInfo();
        bill.showInfo();
    }
    public static class Staff {
        private String fullName;
        private int salary;

        public  Staff(String fullName, int salary) {
            this.fullName = fullName;
            this.salary = salary;
        }

        public String getFullName() {
            return fullName;
        }

        public void setFullName(String fullName) {
            this.fullName = fullName;
        }

        public int getSalary() {
            return salary;
        }

        public void setSalary(int salary) {
            this.salary = salary;
        }

        public void showInfo(){
            System.out.println("fullName: " + this.getFullName() + " Salary: " + this.getSalary());
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值