04 java8实战--常见函数式接口:Function

9 篇文章 0 订阅

1 Function

@FunctionalInterface
public interface Function<T, R> {

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);
  • 接受一个T,返回一个R
    eg:接受一个String,返回Sting对应的hashCode
 @Test
    public void testFunction(){
        Function<String,Integer> hashCode = (p1)->p1.hashCode();
        Integer result = hashCode.apply("java");
        System.out.println(result);
    }

又比如:接受一个int,返回该数的平方

 @Test
    public void testFunction2(){
        Function<Integer,Double> hashCode = p1->Math.pow(p1,2);
        Double result = hashCode.apply(2);
        System.out.println(result);
    }

2 IntFunction,LongFunction,DoubleFunction等

@FunctionalInterface
public interface IntFunction<R> {

    /**
     * Applies this function to the given argument.
     *
     * @param value the function argument
     * @return the function result
     */
    R apply(int value);
}
  • 和之前的LongPredicate,Function也有类似这样一系列的函数式接口(LongFunction,IntFunction),只是明确规定T的类型为int类型而已,只需要声明返回值类型即可
 @Test
    public void testIntFunction2(){
        IntFunction<Double> hashCode = p1->Math.pow(p1,2);
        Double result = hashCode.apply(2);
        System.out.println(result);
    }

3 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);
  • 接受T, U两种类型,返回R类型

eg: 简单来说可以用求两数之和

 @Test
    public void testBiFunction(){
        BiFunction<Integer,Integer,Integer> sumFunction = (a,b)->a+b;
        Integer sum = sumFunction.apply(1, 2);
        System.out.println(sum);
    }

4 ToDoubleBiFunction

@FunctionalInterface
public interface ToDoubleBiFunction<T, U> {

    /**
     * Applies this function to the given arguments.
     *
     * @param t the first function argument
     * @param u the second function argument
     * @return the function result
     */
    double applyAsDouble(T t, U u);
}
  • 说白了就是明确了返回值类型为Double,类似有ToIntBiFunction,ToLongBiFunction,ToDoubleFunction,ToIntFunction,ToLongFunction
@Test
    public void testToDoubleBiFunction(){
        // 计算 a的b次方
        ToDoubleBiFunction<Integer,Integer> doubleBiFunction = (a,b)->Math.pow(a,b);
        double result = doubleBiFunction.applyAsDouble(2, 3);
        System.out.println(result);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值