Java8 lamda表达式快速上手
1.对比着经典foreach
简单的循环
o相当于foreach中的临时变量,要遍历的list放在句首
list.foreach(o->{你要进行的操作});
package com.company; import com.entity.Goods; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<Goods> list = new ArrayList<Goods>(); Goods goods1 = new Goods(1,"健力宝"); Goods goods2 = new Goods(2,"伟哥"); list.add(goods1); list.add(goods2); for(Goods o: list) { // 外部迭代 System.out.println(o); } System.out.println("=============lambda表达式============="); list.forEach(o -> {System.out.println(o);}); } }
2.foreach里面的if功能,即list.stream().filter().foreach()
public List<Photo> buildPhoto() { List<Photo> target = new ArrayList<>(); if (!photoList.isEmpty()) { // 根元素 photoList.stream().filter(photo -> photo.getParentId() == 0).forEach(photo -> { // 根元素 List<Photo> children = getChildren(photo); photo.setChildren(children); target.add(photo); }); // 相当于经典foreach的如下代码 for (Photo photo:photoList){ if (photo.getParentId() == 0){ List<Photo> children = getChildren(photo); photo.setChildren(children); target.add(photo); } } } return target; }
如果想深究其原理 参考http://www.cnblogs.com/aoeiuv/p/5911692.html
作者:Rest探路者
出处:http://www.cnblogs.com/Java-Starter/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意请保留此段声明,请在文章页面明显位置给出原文连接
Github:https://github.com/cjy513203427