码迷,mamicode.com
首页 > 编程语言 > 详细

Java8中数据流的使用

时间:2017-09-25 00:55:02      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:average   min   man   stat   sum   public   gen   last   rgs   

Code:

@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
    private Integer id;
    private Integer age;
    private String gender;
    private String firstName;
    private String lastName;
}

Main:

public class test {
    public static void main(String[] args) throws Exception {

        Employee e1 = new Employee(1, 23, "M", "Rick", "Beethovan");
        Employee e2 = new Employee(2, 13, "F", "Martina", "Hengis");
        Employee e3 = new Employee(3, 43, "M", "Ricky", "Martin");
        Employee e4 = new Employee(4, 26, "M", "Jon", "Lowman");
        Employee e5 = new Employee(5, 19, "F", "Cristine", "Maria");
        Employee e6 = new Employee(6, 15, "M", "David", "Feezor");
        Employee e7 = new Employee(7, 68, "F", "Melissa", "Roy");
        Employee e8 = new Employee(8, 79, "M", "Alex", "Gussin");
        Employee e9 = new Employee(9, 15, "F", "Neetu", "Singh");
        Employee e10 = new Employee(10, 45, "M", "Naveen", "Jain");

        List<Employee> employees = new ArrayList<Employee>();
        employees.addAll(Arrays.asList(new Employee[]{e1, e2, e3, e4, e5, e6, e7, e8, e9, e10}));


        IntSummaryStatistics statistics = employees.stream().mapToInt(o -> o.getAge()).summaryStatistics();
        System.out.println(statistics.getMax());
        System.out.println(statistics.getMin());
        System.out.println(statistics.getSum());
        System.out.println(statistics.getAverage());
        System.out.println(statistics.getCount());
        //从大到小
        List<Employee> list = employees.stream().sorted((a, b) -> b.getAge().compareTo(a.getAge())).limit(3).collect(Collectors.toList());
        System.out.println(JSON.toJSONString(list));

        val list2 = employees.stream().sorted((a, b) -> a.getFirstName().compareTo(b.getFirstName())).limit(3).collect(Collectors.toList());
        System.out.println(JSON.toJSONString(list2));
    }
}

Output:

79
13
346
34.6
10
[{"age":79,"firstName":"Alex","gender":"M","id":8,"lastName":"Gussin"},{"age":68,"firstName":"Melissa","gender":"F","id":7,"lastName":"Roy"},{"age":45,"firstName":"Naveen","gender":"M","id":10,"lastName":"Jain"}]
[{"age":79,"firstName":"Alex","gender":"M","id":8,"lastName":"Gussin"},{"age":19,"firstName":"Cristine","gender":"F","id":5,"lastName":"Maria"},{"age":15,"firstName":"David","gender":"M","id":6,"lastName":"Feezor"}]

 

http://www.yiibai.com/java8/java8_stream.html

Java8中数据流的使用

标签:average   min   man   stat   sum   public   gen   last   rgs   

原文地址:http://www.cnblogs.com/hongdada/p/7589321.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!