java 8 lambda表达式

1.lambda简洁

1.什么是lambda表达式
lambda表达式是java8添加的一个新特性,说白了,他是一个内部函数。
2.为什么要使用lambda表达式
简洁,高效
3.lambda对接口的要求
接口中的抽象方法的个数必须是一个。
4.@FunctionalInterface
这个注解用来申明该接口为函数式接口,这个接口中的抽象方法只能为一个,添加多个会报错。

2.lambda基础语法

()->{}
() 用来描述方法参数,里面可以放多个参数,参数的类型可以不用指定,由编译器识别,{}表示方法体,方法体中根据接口的返回值类型返回对应类型。
例如:
@FunctionalInterface
interface Test{
int action(int a,int b);
}
Test t=(a,b)->{return a-b};

3.方法引用

可以将lambda表达式的实现指向一个已经定义了的方法,这样便于在多处使用相同的lambda表达式中可以省略重复的代码,也便于维护和修改。

@FunctionalInterface
interface Test1{
int add(int a,int b);
}

//预先定义方法给lambda引用
class MainTest{
public static int change(int a,int b){
return a+b;
}
public static void main(String [] args){
Test test1=(a,b) ->change(a,b);
test1.add(5,6);
}
}
方法引用简化
Test test2=MainTest::change;
要求:
该方法中的参数的数量类型以及返回值类型要和函数式接口中的参数一致。
引用方式:
类::实例方法
类::静态方法
对象::实例方法

例:
1.打印集合
list.foreach(x->System.out::println)
2.忽略大小写对字符串数组进行排序
Arrays.sort(strings,(x,y)->x.compareToIgnoreCase(y
))
Arrays.sort(String,String::comporeToIgnoreCase)

4.构造函数引用

class Person{
int id;
String name;
//省略无参有参构造方法
}
interface PersonCreater{
person create();
}
PersonCreater p1=()->new Person();
简化:
PersonCreater p2=()->Person::new;

有参
interface PersonCreater1{
person create(int id,String name);
}

PersonCreater p1=()->new Person(1,“小明”);
Person person = p1.create();
简化:
PersonCreater p2=()->Person::new;
Person person=p2.create(1,“小明”);

5.综合常用案例

1.ArrayList的排序
List persons=new ArrayList();
list.sort(persons,(p1,p2)->p2.getAge()-p1.getAge());
2.TreeSet 排序并且保持不去重元素
Set Person =new TreeSet(
(p1,p2)->{
if(p2.getAge()>=p1.getAge()){
return 1;
}
else{
retrun -1;
}
}
);
然后添加元素输入集合发现TreeSet元素降序未去重。
3.集合遍历
List list=new ArrayList();
Collection.addAll(1,2,3,4,5,6,7,8,9,0);
list.foreach(System.out::println);
//加入逻辑判断
list.foreach(list,number->{
if(number%2==0){
System.out.println(number);
}
});
4.删除元素
list.removeif(e->e.getAge()>10);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值