java8流处理遍历(仅供个人学习)

2020-07-30 22:09:12 浏览数 (1)

代码语言:javascript复制
Map<Long, Long> goodsMap = new HashMap<>();
if (StringUtils.isEmpty(dto.getGoodsCategoryId())) {
    Query query = Query.instance();
    query.setSelectFieldsArray("id", "categoryId");
    query.addInLongWhere("id", dto.getGoodsIds());
    List<GoodsModel> goodsModels = goodsV2Service.queryAll(query);
    // 方法一 使用流处理遍历goodsModels并且放进goodsMap,goodsMap中如果已经存在key则不再放入
    goodsModels.stream().forEach(goodsModel -> goodsMap.computeIfAbsent(goodsModel.getId(), k -> goodsModel.getCategoryId()));
    // 方法二:遍历goodsModels并且放进goodsMap
    for (GoodsModel goodsModel : goodsModels) {
        // goodsMap中如果已经存在key则不再放入
        goodsMap.computeIfAbsent(goodsModel.getId(), k -> goodsModel.getCategoryId());
    }
}
代码语言:javascript复制
// 先过滤条件
goodsModels.stream().filter(goodsModel -> {
    goodsModel.getCategoryId() > 0
}).forEach(
        goodsMap.computeIfAbsent(goodsModel.getId(), k -> goodsModel.getCategoryId());
});

0 人点赞