函数式编程1-Lambda表达式

栏目: 编程语言 · 发布时间: 6年前

内容简介:lambda表达式又称为匿名函数,可以让函数作为其他方法的参数,先举例两个简单的接口:我们可以这样定一个匿名函数:其中

lambda表达式又称为匿名函数,可以让函数作为其他方法的参数,先举例两个简单的接口:

  • java.util.function.Function<T, R>T 为入参类型, R 为返回值类型;
  • java.util.function.BiFunction<T, U, R>T 为第一个参数类型, U 为第二个参数类型, R 为返回值类型。

我们可以这样定一个匿名函数:

Function<Integer,Integer> compute = a -> a + 1;

BiFunction<Integer,Integer,Integer> = (a, b) -> a + b;

其中 -> 前的为入参,后面为计算,若只有一行计算可不用花括号,也不用显式 return 结果。

下面演示两个方法,分别接受 Function , BiFunction 作为入参的示例:

public class DemoLambdas {
    public static Integer computeOne(Function<Integer,Integer> function, Integer value){
        return function.apply(value);
    }


    public static Integer computeTwo(BiFunction<Integer,Integer,Integer> function, Integer value, Integer value2){
        return function.apply(value,value2);
    }

}

在调用处,我们可以通过动态实现Function来实现不同的算法:

log.info(DemoLambdas.computeOne(a -> -a, 5).toString());
log.info(DemoLambdas.computeOne(a -> a - 1, 5).toString());
log.info(DemoLambdas.computeTwo((a, b) -> a + b,10,5).toString());
log.info(DemoLambdas.computeTwo((a, b) -> { Integer c = a - b;
                                            return c + a + b; } ,10,5).toString());

阅读量: 2


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

A Philosophy of Software Design

A Philosophy of Software Design

John Ousterhout / Yaknyam Press / 2018-4-6 / GBP 14.21

This book addresses the topic of software design: how to decompose complex software systems into modules (such as classes and methods) that can be implemented relatively independently. The book first ......一起来看看 《A Philosophy of Software Design》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

URL 编码/解码
URL 编码/解码

URL 编码/解码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器