java8流操作

java8常用特性:

1.爛大街

shopInfoDTOList.stream().map(s -> toShopAuthorizationDTO(s, map)).collect(Collectors.toList());
shopInfoDTOList.stream().distinct().map(s -> toShopAuthorizationDTO(s, map)).collect(Collectors.toList());

2.分組、不分組

moduleCompanyLicenseDOList.stream().collect(Collectors.toMap(a -> a.getModuleId(), a -> a.getId(), (k1, k2) -> k1));
moduleCompanyLicenseDOList.stream().collect(Collectors.groupingBy(ModuleCompanyLicenseDO::getModuleId));

3.過濾

shopAuthorizationDTOList.stream().filter(s -> filterConditions(s, query)).collect(Collectors.toList());

4.分頁

.stream().skip(query.getLimitNum() * (query.getCurrentPage() - 1)).limit(query.getLimitNum()).collect(Collectors.toList());

5.排序

Comparator<Object> compare = Collator.getInstance(Locale.CHINA);
.sort((o1, o2) -> ((Collator) compare).compare(o1.getSimpleName(), o2.getSimpleName()));

6.求和

.stream.reduce((i, j) -> i + j).get();
或
.stream.reduce((i, j) -> i + j).ifPresent(System.out::println);

7. Map排序

正排:map.entrySet().stream().sorted(Comparator.comparingInt(Map.Entry::getValue)).collect(LinkedHashMap::new,(m,e) -> m.put(e.getKey(),e.getValue()),LinkedHashMap::putAll);

倒排:map.entrySet().stream().sorted(Comparator.comparingInt((Map.Entry<String,Integer> m) -> m.getValue()).reversed()).collect(LinkedHashMap::new,(m,e) -> m.put(e.getKey(),e.getValue()),LinkedHashMap::putAll);

8.示例:

public static PageInfo getPageInfo(ShopAuthorizationQueryRequest query, List<ShopAuthorizationDTO> shopAuthorizationDTOList) {
        PageInfo pageInfo = new PageInfo<>();
        // 根據查詢條件過濾數據
        shopAuthorizationDTOList = shopAuthorizationDTOList.stream().filter(s -> filterConditions(s, query)).collect(Collectors.toList());
        // 排序
        Comparator<Object> compare = Collator.getInstance(Locale.CHINA);
        shopAuthorizationDTOList.sort((o1, o2) -> ((Collator) compare).compare(o1.getSimpleName(), o2.getSimpleName()));
        pageInfo.setTotal(shopAuthorizationDTOList.size());
        shopAuthorizationDTOList = shopAuthorizationDTOList.stream().skip(query.getLimitNum() * (query.getCurrentPage() - 1)).limit(query.getLimitNum()).collect(Collectors.toList());
        pageInfo.setList(shopAuthorizationDTOList);
        return pageInfo;
    }
 /**
     * 過濾條件
     * @param s
     * @param query
     * @return
     */
    private static boolean filterConditions(ShopAuthorizationDTO s,ShopAuthorizationQueryRequest query){
        boolean flag =true;
        if(query.getShopId() != null){
            flag &= query.getShopId().equals(s.getShopId());
        }
        if (query.getPlatFormType() != null) {
            flag &= query.getPlatFormType().equals(s.getPlatFormType());
        }
        if(query.getAuthorizationType() != null){
            flag &= query.getAuthorizationType().equals(s.getAuthorizationType());
        }
        return flag;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章