Java8中数据流的使用

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

posted @   hongdada  阅读(727)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示