Lambda表达式经典应用场景

1.取出List中的所有收付款流水的最大/最小创建时间

// fmDebitCreditPayReceiveList  最小创建时间收付款流水
FmDebitCreditPayReceiveList fmDebitCreditPayReceiveList = null;
Optional<FmDebitCreditPayReceiveList> optional = fmPayReceiveListPageInfo.getList()
	.stream().filter(Objects::nonNull)
	.filter(x -> x != null && x.getCreateTime() != null)
	.sorted(Comparator.comparing(FmDebitCreditPayReceiveList::getCreateTime))
	.findFirst();
fmDebitCreditPayReceiveList = optional.isPresent() ? optional.get() : new FmDebitCreditPayReceiveList();
// 这里注意一下optional必须先调用isPresent()方法之后才能调用get()方法

想要获取最大创建时间收付款流水的话,加上reversed倒排序即可
.sorted(Comparator.comparing(FmDebitCreditPayReceiveList::getCreateTime)
.reversed)

2.获取List中的某一列的值

获取销售订单List中实体的所有订单编号
List<String> codeList = SaleOrderList.stream().map(SaleOrderEntity::getOrderCode)
.collect(Collectors.toList()));

3.获取List中经过筛选后按照某个条件分组的Map

// 筛选出所有AMOUNT_TYPE(代收代付类型)的销售订单并按照计费方式分组
Map<Integer, List<SaleOrderEntity>> saleOrderMap = saleOrderList.stream()
	.filter(x -> AMOUNT_TYPE.equals(x.getType()))
	.collect(Collectors.groupingBy(SaleOrderEntity::getPricingType));
// map中有一个好用的防空的方法, 获取map中对应code的值,没有的就默认0L
saleOrderMap.getOrDefault(saleOrderEntity.getCode, 0L);

4.lambda表达式List构造Map

// 构造一个键是订单编号,值是实提重量的Map
Map<String, Long> orderMap = saleOrderEntityList.stream()
	.collect(Collectors.toMap(SaleOrderEntity::getOrderCode,
	SaleOrderEntity::getSumDeliveryQTty));

// 如果希望得到 Map 的 value 为对象本身时,可以这样写:
userList.stream().collect(Collectors.toMap(User::getId, t -> t));
 或:
userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));

// Collectors.toMap 有三个重载方法:
toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper);
toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper,
        BinaryOperator<U> mergeFunction);
toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper,
        BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier);

参数含义分别是:

keyMapper:Key 的映射函数

valueMapper:Value 的映射函数

mergeFunction:当 Key 冲突时,调用的合并方法

mapSupplier:Map 构造器,在需要返回特定的 Map 时使用

// 当key冲突时就需要调用第二个重载方法,传入合并函数,如:
userList.stream().collect(Collectors.toMap(User::getId, User::getName, (n1, n2) -> n1 + n2));

// 输出结果:
A-> 张三李四 
C-> 王五 

// 第四个参数(mapSupplier)用于自定义返回 Map 类型,比如我们希望返回的 Map 是根据 Key 排序的,可以使用如下写法:
List<User> userList = Lists.newArrayList(
        new User().setId("B").setName("张三"),
        new User().setId("A").setName("李四"),
        new User().setId("C").setName("王五")
);
userList.stream().collect(
    Collectors.toMap(User::getId, User::getName, (n1, n2) -> n1, TreeMap::new)
);

// 输出结果:
A-> 李四 
B-> 张三 
C-> 王五 

5.汇总List某个的数字

BigDecimal totalAmount = saleOrderEntityList.stream()
.map(SaleOrderEntity::getAmount)
.reduce(BigDecimal.ZERO, BigDecimal::add)

6.List的forEach()方法

param(参数):(Consumer<? super T> action)函数式接口
单个参数无返回值
@FunctionalInterface
public interface Consumer<T> {
    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);
}

应用实例:

List<FmInterestRule> fmInterestRules = fmInterestRuleService.getFmInterestRuleByRelationId(presellId);
        List<FmInterestRuleVO> fmInterestRuleVOS = new ArrayList<>();
        fmInterestRules.forEach(x -> {
            FmInterestRuleVO fmInterestRuleVO = new FmInterestRuleVO();
            BeanUtils.copyProperties(x, fmInterestRuleVO);
            fmInterestRuleVOS.add(fmInterestRuleVO);
        });

7.Map的forEach()方法

param(参数):(BiConsumer<? super K, ? super V> action)  函数式接口
两个参数无返回值
@FunctionalInterface
public interface BiConsumer<T, U> {
    /**
     * Performs this operation on the given arguments.
     *
     * @param t the first input argument
     * @param u the second input argument
     */
    void accept(T t, U u);
}

应用实例:

Function<FmContractInterestCaculate, String> f = x ->  Instant.ofEpochMilli(x.getInterestTime()).atZone(ZoneId.systemDefault()).toLocalDate().format(DateTimeFormatter.ofPattern("yyyy-MM"));; 
        Map<String, List<FmContractInterestCaculate>> collect = interestList.stream().collect(Collectors.groupingBy(f));
        List<ContractInterestCaculateDTO> retList = new  ArrayList<>(collect.size());
        collect.forEach((k, contractInterestList) -> {
            ContractInterestCaculateDTO vo = new ContractInterestCaculateDTO();
            vo.setItems(contractInterestList);
            vo.setInterestMonth(k);
            FmContractInterestCaculate lastContractInterest = contractInterestList.get(contractInterestList.size() - 1);
            vo.setContractId(lastContractInterest.getContractId());
            vo.setContractCode(lastContractInterest.getContractCode());
            vo.setRate(lastContractInterest.getRate());
            BigDecimal phaseEnd = lastContractInterest.getPhaseEnd();
            BigDecimal phaseBegin = contractInterestList.get(0).getPhaseBegin();
            vo.setPhaseBegin(phaseBegin);
            vo.setPhaseEnd(phaseEnd);
            vo.setRedemptionAmount(phaseBegin.subtract(phaseEnd));
            // 合计大于0 的计息金额
            Double sumInterestAmount = contractInterestList.stream().filter(x -> x.getInterestAmount().doubleValue() > 0).mapToDouble(x -> x.getInterestAmount().doubleValue()).sum();
            vo.setInterestAmount(BigDecimal.valueOf(sumInterestAmount).setScale(2, BigDecimal.ROUND_HALF_UP)); 
            retList.add(vo);
        });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值