使用
(params) -> expression
(params) -> statement
(params) -> { statements }
注意:
1.lambda表达式有个限制,那就是只能引用 final 或 final 局部变量,这就是说不能在lambda内部修改定义在域外的变量。
List primes = Arrays.asList(new Integer[]{2, 3,5,7});
int factor = 2;
primes.forEach(element -> { factor++; });
Compile time error : "local variables referenced from a lambda expression must be final or effectively final"
1.列表操作
1.简单循环列表
//初始化数据
List books=Arrays.asList(new Books("西游记",15),new Books("java",20),
new Books("金瓶梅",10),new Books("水湖庄",30));
//循环书名
books.forEach(books1 -> System.out.println("书名:"+books1.getName()+" 价格:"+books1.getPrice()));
2.过滤数据
//过滤价格
List highPrice=books.stream().filter(books1 -> books1.getPrice()>15).collect(Collectors.toList());
highPrice.forEach(highbook-> System.out.println("价格高于15的书:"+highbook.getName()));
3.排序
System.out.println("从低到高排序");
List sortBooks=books.stream().sorted(Comparator.comparing(Books::getPrice)).collect(Collectors.toList());
sortBooks.forEach(book-> System.out.printf("书名:%s,价格:%s\n",book.getName(),book.getPrice()));
System.out.println("从高到低排序");
List sortBooks2=books.stream().sorted(Comparator.comparing(Books::getPrice).reversed()).collect(Collectors.toList());
sortBooks2.forEach(book-> System.out.printf("书名:%s,价格:%s\n",book.getName(),book.getPrice()));
4.书本价格相加
int totalPrice=books.stream().map(Books::getPrice).reduce(0,(a,b)->a+b);
System.out.println(totalPrice);
5.去重
//使用distinct 方法去重
List numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4);
List distinct = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
System.out.printf("Original List : %s, Square Without duplicates : %s %n", numbers, distinct);
替代内部类
//替代内部类
public void test2(){
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Before Java8, too much code for too little to do");
}
}).start();
new Thread( () -> System.out.println("In Java8, Lambda expression rocks !!") ).start();
}
简单的用可以,如果链条太长的话,有时候会让代码反而更加难看懂