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

posted @ 2017-08-24 17:34  Rest探路者  阅读(397)  评论(0编辑  收藏  举报
levels of contents