Function和BiFunction详解

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

  • 7
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值