Java lamda表达式常用demo

  1. lamda表达式
    public static String extractIdFromTags(List<String> tags) {
        if (CollectionUtils.isEmpty(tags)) return "";
    
        List<String> validYears = Arrays.asList("2023", "2024", "2025", "2026", "2027");
    
        String txid = tags.stream()
                .filter(x -> validYears.stream().anyMatch(year -> x.startsWith(year)))
                .filter(x -> x.length() > 20 && x.length() <= 32)
                .findFirst()
                .orElse("");
    
        return txid.toUpperCase();
    }
    

    判断字符串是否以指定的年份开头,并且长度大于20且小于等于32,可以对条件进行组合判断

  2. BigDecimal sum = successNumVos.stream().map(x -> Optional.ofNullable(x.getSuccessAmount()).orElse(BigDecimal.ZERO)).reduce(BigDecimal.ZERO, BigDecimal::add);
    

     

  3. List<MianshiLogical> list = new ArrayList<>();
    // 假设你有一个包含MianshiLogical对象的列表list
    
    // 使用Java Lambda根据logialCategory进行分组
    Map<String, List<String>> groupedMap = list.stream()
            .collect(Collectors.groupingBy(MianshiLogical::getLogialCategory,
                    Collectors.mapping(MianshiLogical::getLogialNum, Collectors.toList())));

     

  4.  List<Integer> roleIdList = Arrays.asList(16, 17, 18, 22, 26);
                List<UserRole> filterList = list.stream()
                        .filter(x -> roleIdList.contains(x.getRoleId()))
                        .collect(Collectors.toList());
  5. Map<String, List<AccountWeightVo>> weightMap = paymentAccount.stream()
            .collect(Collectors.groupingBy(MerchantAccountRecord::getMerchantId,
                    Collectors.mapping(record -> new AccountWeightVo(record.getAccountId(), record.getWeight()), Collectors.toList())));

     

发表评论

邮箱地址不会被公开。