使用
(params) -> expression
(params) -> statement
(params) -> { statements }
注意:
1.lambda表達式有個限制堪澎,那就是只能引用 final 或 final 局部變量,這就是說不能在lambda內(nèi)部修改定義在域外的變量味滞。
List<Integer> 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.簡單循環(huán)列表
//初始化數(shù)據(jù)
List<Books> books=Arrays.asList(new Books("西游記",15),new Books("java",20),
new Books("金瓶梅",10),new Books("水湖莊",30));
//循環(huán)書名
books.forEach(books1 -> System.out.println("書名:"+books1.getName()+" 價格:"+books1.getPrice()));
image.png
2.過濾數(shù)據(jù)
//過濾價格
List<Books> highPrice=books.stream().filter(books1 -> books1.getPrice()>15).collect(Collectors.toList());
highPrice.forEach(highbook-> System.out.println("價格高于15的書:"+highbook.getName()));
image.png
3.排序
System.out.println("從低到高排序");
List<Books> 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<Books> 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()));
image.png
4.書本價格相加
int totalPrice=books.stream().map(Books::getPrice).reduce(0,(a,b)->a+b);
System.out.println(totalPrice);
5.去重
//使用distinct 方法去重
List<Integer> numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4);
List<Integer> distinct = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
System.out.printf("Original List : %s, Square Without duplicates : %s %n", numbers, distinct);
image.png
替代內(nèi)部類
//替代內(nèi)部類
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();
}
簡單的用可以全封,如果鏈條太長的話,有時候會讓代碼反而更加難看懂