Java8 Lambda代码备份

简单研究了一下,贴出来,相当于笔记

import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import com.google.gson.Gson;

public class Hello {

    public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

        try {
            // Java中Lambda表达式
            List<Student> list = new ArrayList<Student>();
            list.add(new Student("zhangsan", 20, "2"));
            list.add(new Student("lisi", 22, "2"));
            list.add(new Student("zhangjie", 25, "3"));
            list.add(new Student("zhangjie", 40, "3"));

            // 循环赋值,增加2岁
            list.forEach(item -> item.setAge(item.getAge() + 2));

            // 循环输出年龄
            list.forEach(item -> System.out.println(item.getAge()));

            // 总数、最大值、最小值
            int ages = list.stream().mapToInt(f -> f.getAge()).sum();
            int maxAge = list.stream().mapToInt(f -> f.getAge()).max().getAsInt();
            System.err.println("总年龄是:" + ages);
            System.err.println("最大年龄是:" + maxAge);

            // 分组
            list.stream().collect(Collectors.groupingBy(Student::getName, Collectors.toList()))//
                    .forEach((name, fooListByName) -> System.out.println(name + " " + new Gson().toJson(fooListByName)));

            list.stream().collect(Collectors.groupingBy(Student::getName, Collectors.counting()))//
                    .forEach((name, count) -> System.out.println(name + " " + count));

            list.stream().collect(Collectors.groupingBy(Student::getName, Collectors.toList()))//
                    .forEach((name, ls) -> System.out.println("姓名:" + name + ",最大年龄" + ls.stream().mapToInt(f -> f.getAge()).max().getAsInt()));
                    
            //分页
            List<Student> arr = list.stream().skip(0).limit(5).collect(Collectors.toList());
            
            //where查询
            List<TaskPro> list= taskPros.stream().filter(f->f.getFirmId().equals("199989494")&&//
                        f.getTaskId().equals("1000")).collect(Collectors.toList());
        } finally {
        }

    }

}

 

posted @ 2017-07-07 11:22  段江涛IT  阅读(286)  评论(0编辑  收藏  举报
页脚HTML代码