java8特性使用技巧

1.List-》Map

List<MarketExecPojo> bondsExecPojos = queryRemoteData(s);
 Map<String, List<MarketExecPojo>> xBondMap = bondsExecPojos.stream()
                        .filter(i -> "有效".equals(i.getExecType()))
                        .collect(Collectors.groupingBy(MarketExecPojo::getBondCode));

2.排序sorted

List<BusinessSoundPojo> value = entry.getValue().stream().sorted(Comparator.comparing(BusinessSoundPojo::getSeqNo)).collect(Collectors.toList());
#reversed从大到小
List<AbstractQuoteDepth> quoteDepthList = quoteDepthListOld.stream().sorted(Comparator.comparingDouble(AbstractQuoteDepth::getPrice)
    .reversed().thenComparingLong(AbstractQuoteDepth::getSendingTime)).collect(Collectors.toList());

 

3.map的使用

将getApplCode作为List里面的值

List<String> applCodes = roles.stream().map(Role::getApplCode).collect(Collectors.toList());

 

4.allMatch(),anyMatch(),noneMatch()使用

allMatch:必须全都符合

anyMatch:符合一个就可以

noneMatch:全部都不符合

    private boolean checkDuplicate(Set<String> selfSet, Set<String> themSet) {
        return themSet.stream().anyMatch(key -> {
            boolean duplicated = selfSet.contains(key);
            if (duplicated) {
                LOGGER.warn("the configKey [{}] is duplicated.", key);
            }
            return duplicated;
        });
    }

详细参考:https://www.jianshu.com/p/6950c8b61ccd

 

5.distinct去重

String temp = list.stream().distinct().collect(Collectors.joining(BaseConstant.COMMA));

6.flatMap的使用

    private static final Map<String, Map<Integer, Map<String, CurvePojo>>> CURVE_GROUP_DEFINITION_MAP = new HashMap<>();
CURVE_GROUP_DEFINITION_MAP.values().stream()
            .flatMap(i -> i.values().stream().flatMap(j -> j.values().stream()))
            .anyMatch(i -> i.getCurrency().equals(currency));

 

posted @ 2024-02-05 17:07  WXY_WXY  阅读(24)  评论(0)    收藏  举报