java的lambda表达式和Stream如何使用???
Lambda表达式的语法
基本语法:
(parameters) -> expression
或
(parameters) ->{ statements; }
看例子学习吧!
例一:定义一个AyPerson类,为之后的测试做准备。
package com.evada.de;
import java.util.Arrays;
import java.util.List;
class AyPerson{
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public AyPerson(String id, String name) {
this.id = id;
this.name = name;
}
}
/**
* Created by Ay on 2016/5/9.
*/
public class LambdaTest {
public static void main(String[] args) {
List<String> names = Arrays.asList("Ay", "Al", "Xy", "Xl");
names.forEach((name) -> System.out.println(name + ";"));
}
}
上面的例子names.forEach((name) -> System.out.println(name + “;”));
类似于:
function(name){//name为参数
System.out.println(name + “;”);//方法体
}
结果:
Ay;
Al;
Xy;
Xl;
例二:把下面代码copy到上面main函数中
List<Student> personList = new ArrayList<>();
personList.add(new Student("00001","Ay"));
personList.add(new Student("00002","Al"));
personList.add(new Student("00003","To"));
personList.forEach((person) -> System.out.println(person.getId()+ ":" + person.getName()));
结果:
00001:Ay
00002:Al
00003:To
例三:Lambda和Stream类中f**ilter()**方法
List<AyPerson> personList = new ArrayList<>();
personList.add(new AyPerson("00001","Ay"));
personList.add(new AyPerson("00002","Al"));
personList.add(new AyPerson("00003", "To"));
//stream类中的filter方法
personList.stream()
//过滤集合中person的id为00001
.filter((person) -> person.getId().equals("00001"))
//将过滤后的结果循环打印出来
.forEach((person) -> System.out.println(person.getId() + ":" + person.getName()));
结果:
00001:Ay
例四:Stream类中的collect()方法,
List<AyPerson> personList = new ArrayList<>();
List<AyPerson> newPersonList = null;
personList.add(new AyPerson("00001","Ay"));
personList.add(new AyPerson("00002","Al"));
personList.add(new AyPerson("00003", "To"));
//将过滤后的结果返回到一个新的List中
newPersonList = personList.stream()
.filter((person) -> person.getId().equals("00002")).collect(Collectors.toList());
//打印结果集
newPersonList.forEach((person) -> System.out.println(person.getId() + ":" + person.getName()));
除了可以放到List中,还可以放到Set中等等…
结果:
00002:Al
Stream中还有很多好用的方法可以使用,例如count,limit等等可以自己到API学习
来自《萤火虫之墓》
如果有带给你一丝丝小快乐,就让快乐继续传递下去,欢迎转载,点赞,顶,欢迎留下宝贵的意见,多谢支持!