Java8特性系列Lambdas四 组合应用

本文介绍了如何使用Java Stream API中的Comparator、Predicate及Function接口进行条件组合,实现复杂的数据筛选和排序功能。示例包括复合排序标准、多条件过滤以及函数操作的组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

条件组合

  • Comparator的组合

接着上一节,排序问题,我们可以组合多个条件进行排序:

studentQueryService.getStudentList().sort(comparingDouble(Student::getAvgScore))
        .reversed()  //倒叙排
        .thenComparing(Student::getAge() //当有相同的平均分时,按照年龄再排序

  • Predicate的组合

找到平均分>75并且(名字中含有“李”或者年龄>8)

    @Test
    public void testFilterByStreaming(){
        Predicate<Student> predicate = (s) -> s.getAvgScore() > 75;
        predicate.and( s -> s.getCnName().indexOf("李")!=-1)
                .or(s -> s.getAge() > 8);
    }

  • Function<T, R>的组合
    @Test
    public void testFunctionCompose(){
        Function<Integer, Integer> f = (x) -> x + 1;
        Function<Integer, Integer> g = x -> x * 2;
        Function<Integer, Integer> h = f.andThen(g); //g(f(x)) = (3 + 1) * 2 = 8
        Function<Integer, Integer> h1 = f.compose(g); //f(g(x)) = (3 * 2) + 1 = 7
        System.out.println(f.apply(3) + ", " + g.apply(3) + ", " + h.apply(3) + ", " + h1.apply(3));
    }

示例代码下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值