提出问题
解决问题
Lambda表达式的语法
基本语法:
[code](parameters) -> expression
或
(parameters) ->{ statements; }看例子学习吧!
例一:定义一个AyPerson类,为之后的测试做准备。
[code]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 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 + “;”);//方法体
}结果:[code]Ay; Al; Xy; Xl;
例二:把下面代码copy到上面main函数中
立即学习“Java免费学习笔记(深入)”;
[code]ListpersonList = 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()));
结果:
[code]00001:Ay 00002:Al 00003:To
例三:Lambda和Stream类中f**ilter()**方法
[code]ListpersonList = 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()));
结果:
[code]00001:Ay
例四:Stream类中的collect()方法,
[code] ListpersonList = new ArrayList<>(); List 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中等等…
结果:
[code]00002:Al
Stream中还有很多好用的方法可以使用,例如count,limit等等可以自己到API学习
以上就是Java之Lambda表达式和Stream类简单例子的内容,更多相关内容请关注PHP中文网(www.php.cn)!










