java调用闭包对象_java 优雅的使用lambda表达式和闭包

本文介绍了Java 1.8中引入的Lambda表达式,通过示例展示了如何用Lambda简化代码,如集合排序和输出。同时解释了Lambda的实质——简化匿名内部类的使用。此外,文章还探讨了闭包的概念,如何通过对象包裹变量来实现闭包,并通过斐波那契数列的例子说明闭包的应用。
摘要由CSDN通过智能技术生成

java 1.8 加入了lambda的语法,使用lambda语法糖可以让我们的代码更简洁优雅,写起来更爽。

下面看个例子感受一下 :

这个例子中实现student集合的排序和循环输出

public class Lambda {

@Getter

@Setter

@AllArgsConstructor

static class Student{

String name;

Integer age;

@Override

public String toString() {

return "Student{" +

"name='" + name + '\'' +

", age=" + age +

'}';

}

}

public static void main(String[] args) {

List list = Arrays.asList(

new Student("a",10)

,new Student("b",30)

,new Student("c",15)

,new Student("d",20));

//排序

list.sort((x,y)->x.getAge()-y.getAge());

//循环输出

list.forEach(System.out::println);

}

上面的代码实现了student对象集合的排序和循环输出。

是不是相比普通的写法简洁了许多。

lambda代替了什么

我们知道lambda是一种语法糖,那么我们简写了什么呢?

list.sort((x,y)->x.getAge()-y.getAge());//排序

比如上面这行代码,sort的参数是一个Comparator类型的对象

default void sort(Comparator super E> c)

Comparator是一个接口,其中只有一个方法需要被实现,就是compare方法。所以实际上我们是写了一个内部类

int compare(T o1, T o2);

内部类

那么如果是没有lambda之前是什么样呢,我们看一下:

list.sort((x,y)->x.getAge()-y.getAge());//lambda

list.sort(new Comparator() {//内部类

@Override

public int compare(Student o1, Student o2) {

return o1.getAge()-o2.getAge();

}

});

可以看出lambda的强大了吧,写起来就是爽。

在jdk中一般可以用lambda简写的接口都会有@FunctionalInterface注解。

我们也可以称之为函数。

一个标准的lambda由下面的结构构成

(参数,参数)->{

方法体

return 返回值

}

简化结构

参数支持类型推导,所以我们不必写参数的类型

当大于等于两个参数时要用括号包起来,一个参数则不用

如果方法体内只有一行代码,可以省略花括号。并且如果有返回值,那么会将这一行代码的结果作为返回值

//定义函数

@FunctionalInterface

interface fun{

int f(T t);

}

//通过函数获取age

public int getAgeByFun(Student student,fun fun){

return fun.f(student);

}

//函数fun要求 输入T 返回一个int

//我们来实现一个从student对象获取年龄的fun函数

//完整结构

fun fun = (student -> {

return student.getAge();

});

//简写

fun fun2 =s ->s.getAge();

继续简写

上面的例子如果使用编辑器,会提示可以优化语法。然后回变成这个样子。

fun fun3 = Student::getAge;

什么情况可以简写呢

lambda表达式的参数只有一个

当书写的方法体中,只调用一个方法,并且方法的参数列表和lambda的参数列表一致。

当lambda需要返回值时,方法的返回值和lambda的返回值一致

书写的格式为 调用对象::调用方法

静态方法

比如上面的sort,我们定义一个静态方法,然后就可以这样用了

public static int staticM(Student Student){

return student.getAge();

}

//这里 调用对象::调用方法

//调用对象是类 Lambda 调用方法静态方法是 staticM

fun fun = Lambda::staticM;

前面的 list.forEach(System.out::println);也是一样的用法。

调用对象的方法

public int NotstaticM(Student Student){

return student.getAge();

}

//我们可以使用对象::方法

Lambda lambda = new Lambda();

fun fun = lambda::NotstaticM;

//如果在对象的方法内也可以使用this

fun fun2 = this::NotstaticM;

调用参数本身的方法

//调用参数的方法时,因为lambda的参数已经被我们省略掉了

//所以用参数的类型::方法名

fun fun3 = Student::getAge;

java8提供的Function

//stream 对集合操作非常方便

List collect = list.stream().

sorted(Comparator.comparingInt(Student::getAge)) //排序

.peek(System.out::println) //输出

.map(Student::getAge)//转成age int类型集合

.collect(Collectors.toList());//收集起来

//Optional 对 null判断的优化

Student none = null;

Optional.ofNullable(none)

.ifPresent(System.out::println);//当对象不为空时才执行此表达式

//map 的如果没有就添加

//如果这个key没有值。就调用函数创建一个对象,put进去并返回

Map map = new HashMap<>();

Student student = map.computeIfAbsent("aaa", k -> new Student("aaa", 1));

还有更多就不一一列举

像一些策略模式,状态机等设计模式都可以用函数的思想来编写。

闭包

闭包的概念

函数可以访问函数外部的变量,并且与它建立联系,可以修改变量和读取到外部对变量的修改

首先lambda表达式可以使用表达式外的变量,但要求使用的变量是final的,(逻辑上要求,并不强制要求final修饰)

@FunctionalInterface

interface fun {

void f();

}

@Setter

@Getter

@AllArgsConstructor

static class MyInter{

Integer i;

}

public static void main(String[] args) {

Integer a = 1;

fun fun = ()->System.out.println(a);

//a=2;

}

我们使用了变量a,这是没问题的。

但是如果我们再加一行 a =2; 那么就会编译报错,如果我们在lambda里面修改了a也是不行的。

java编译时已经强制要求lambda使用的变量不可修改了,所以final关键字不是必须的。

不能修改那么就达不成闭包的条件。

哪有什么办法可以修改呢

答案是用一个对象包起来

@FunctionalInterface

interface fun {

void f();

}

@Setter

@Getter

@AllArgsConstructor

static class MyInter{

Integer i;

}

public static void main(String[] args) {

MyInter inter = new MyInter(1);

fun fun = ()->inter.setI(2);

fun.f();

System.out.println("lambda修改后:"+inter.getI());

inter.setI(3);

System.out.println("直接修改后:"+inter.getI());

}

我们用一个MyInter对象把变量a封装起来。不修改MyInter对象,而修改它的属性,这样就可以实现了。

输出为

lambda修改后:2

直接修改修改后:3

这就达成了闭包的条件.

闭包的价值

举个栗子:打印给定数量的 斐波那契数列

用闭包实现的例子:

@FunctionalInterface

interface fun {

int f();

}

@Setter

@Getter

@AllArgsConstructor

static class MyInter {

Integer i;

}

public static void main(String[] args) {

print(10);

}

public static void print(int n) {

MyInter last = new MyInter(0);

MyInter next = new MyInter(1);

fun fun = () -> {

int r = next.getI();

int i = last.getI() + next.getI();

last.setI(next.getI());

next.setI(i);

return r;

};

for (int i = 0; i < n; i++) {

System.out.println(fun.f());

}

}

使用闭包就是这么简单。当然实际写的还是挺多的也不咋优雅,使用调方法的方式也可以实现。如果是其它语言会更简洁。

比如go:

func main() {

n:=10

last, next := 0, 1

f := func() int {

last, next = next, (last + next)

return last

}

for i := 0; i < n; i++ {

fmt.Println(f())

}

}

差距好大,希望java能多学习学习其它语言的优势。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值