JDK1.8学习笔记2-函数式接口

本文详细介绍了JDK1.8中的函数式接口,包括基本用法、compose和andThen方法的运用,双参数和断言函数式接口的特性,并通过示例展示了各种接口的实际操作和结果。
摘要由CSDN通过智能技术生成

1Function函数式接口

1.1基本用法

抽象接口

  • apply—将此函数应用于给定的参数

默认实现接口

  • compose—将compose传入函数的返参作为当前函数的入参
  • andThen—将当前函数的返参作为andThen的入参

1.2 compose方法

public class FunctionTest {
   
    public static void main(String[] args) {
   
        FunctionTest functionTest = new FunctionTest();

        System.out.println(functionTest.compute(1, value ->  2 * value));
        System.out.println(functionTest.compute(2, value -> 5 + value));
        System.out.println(functionTest.compute(3, value -> value * value));
        System.out.println(functionTest.convert(4, value -> value + " convert"));
        //
  		Function<Integer, Integer> function = value -> 2 * value;
        System.out.println(functionTest.compute(1, function));
    }

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

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

高阶函数:—接收一个函数作为参数,或者将一个函数作为返回值的函数

1.3 compose方法

示例

public class FunctionTest2 {
   
    public int composeTest(int a, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
   
        return function1.compose(function2).apply(a);
    }

    public static void main(String[] args) {
   
        FunctionTest2 functionTest2 = new FunctionTest2();
        System.out.println(functionTest2.composeTest
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JDK 1.8中,函数接口(Functional Interface)是一个核心概念。如果一个接口有且只有一个未实现的方法,那么这个接口就被称为函数接口。在JDK 1.8中引入了一个新的注解@FunctionalInterface,将这个注解放在接口定义之前,就表示这个接口是一个函数接口。编译器会检查该接口是否只有一个未实现的方法,如果定义了多个或者没有定义,编译器会报错。尽管这个注解不是必须的,但虚拟机仍然能够识别出函数接口。这个注解的主要作用是防止误操作,加了这个注解之后接口将不允许出现多个未实现的方法。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [jdk1.8之函数接口](https://blog.csdn.net/liu_shi_jun/article/details/128562977)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [JDK1.8新特性--函数接口(详解)](https://blog.csdn.net/Saintmm/article/details/109557103)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值