Java8 新特性 - Stream流相关函数练习题(二)

该代码示例展示了如何使用JavaStreamAPI来处理学生列表,包括过滤、映射和聚合操作。具体任务包括统计特定小区的学生总数、打印指定小区学生姓名、计算特定小区学生的平均年龄以及找出年龄大于平均年龄的学生姓名。
摘要由CSDN通过智能技术生成
/*      1) javabean类
        学生类  姓名 年龄 性别 小区
        小区类  地址 小区名 总人数
        性别类  男 女
*/
        ArrayList<StreamStudent> list = new ArrayList<>();
        list.add(new StreamStudent("小王", 21, new StreamSex("男"), new StreamCommunity("上海", "海德堡", 200)));
        list.add(new StreamStudent("小李", 22, new StreamSex("男"), new StreamCommunity("天津", "3区", 215)));
        list.add(new StreamStudent("小赵", 23, new StreamSex("女"), new StreamCommunity("北京", "海德堡", 3121)));
        list.add(new StreamStudent("小白", 24, new StreamSex("男"), new StreamCommunity("南京", "阳光丽兹", 2111)));
        list.add(new StreamStudent("小王", 22, new StreamSex("男"), new StreamCommunity("上海", "2区", 982)));
//      1. 汇总小区名为"海德堡"的学生的总数;
        int sum = list.stream()
                .filter(e -> e.getStreamCommunity().getCommuntityName().equals("海德堡"))
                .mapToInt(a -> a.getStreamCommunity().getSum())
                .sum();
        System.out.println(sum);
//      2. 汇总小区名为"海德堡"的学生的姓名集合;
        list.stream()
                .filter(e -> e.getStreamCommunity().getCommuntityName().equals("海德堡"))
                .map(StreamStudent::getName)
                .forEach(System.out::println);
//      3. 返回住在阳光丽兹+海德堡的学生的平均年龄;
        OptionalDouble average = list.stream()
                .filter(e ->
                        e.getStreamCommunity().getCommuntityName().equals("海德堡") || e.getStreamCommunity().getCommuntityName().equals("阳光丽兹")
                )
                .mapToInt(e -> e.getAge()).average();
        System.out.println(average);
//      4.拿到年龄大于平均年龄的所有学生的姓名集合;
        double average1 = list.stream()
                .mapToInt(StreamStudent::getAge)
                .average().getAsDouble();
        System.out.println(average1);

        list.stream()
                .filter(e -> e.getAge() > average1)
                .map(streamStudent -> streamStudent.getName())
                .forEach(System.out::println);

        for (StreamStudent e : list) {
            if (e.getAge() > average1) {
                String name = e.getName();
                System.out.println(name);
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值