Java8 新特性

Optional 相关操作

Stream 相关操作

1、List 转Map<Integer,String>

Map<Integer,String> roadMap = dtoList.stream().collect(Collectors.toMap(MaintPlanBaseDTO::getId, MaintPlanBaseDTO::getRoadCode));

2、List 转 Map<Integer,Object>

Map<Integer, BdataOrgContactDTO> map = dtoList.stream()
        .collect(Collectors.toMap(BdataOrgContactDTO::getDataId, s -> s, (s1, s2) -> s2));

3、List 转 Map<String ,List>

Map<String, List<ApprovalRecordDTO>> map = recordList.stream().collect(Collectors.groupingBy(s -> s.getAfId() + "_" + s.getUserId()));

4、List 转 List

List<Long> ids = vos.stream().map(HighwayListVO::getId).distinct().collect(Collectors.toList());

5、String 转 List
例如:String strArr= "1,2,3,4,5,6" -> List listLong [1,2,3,4,5,6];

  public static List<Integer> stringToIntegerList(String strArr) {
        return Arrays.stream(strArr.split(","))
                .map(s -> Integer.parseInt(s.trim()))
                .collect(Collectors.toList());
    }

6、flatMap

List<String> asia = Arrays.asList("中国", "日本", "新加坡");
        List<String> american = Arrays.asList("美国", "加拿大", "巴拿马");


        List<List<String>> country = new ArrayList<>();
        country.add(asia);
        country.add(american);

        List<String> allContry = new ArrayList<>();

        for (List<String> team : country) {
            for (String name : team) {
                allContry.add(name);
            }
        }
        /**java8之前遍历方式*/
        System.out.println(allContry);

        /**java8遍历方式*/
        List<String> flatMapList = country.stream()
                .flatMap(pList -> pList.stream())
                .collect(Collectors.toList());

8、List 过滤数据

    List<ServiceAreaParkSpaceVO> upList = serviceAreaParkSpaceList.stream().filter(s -> s.getDirection().intValue() == 1).collect(Collectors.toList());

9、根据集合中的某个字段去重:

   ArrayList<TrafficSituationAnalysisVO> collect = trafficSituationAnalysisList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TrafficSituationAnalysisVO::getTimeStr))), ArrayList::new));

10、List 排序

   list = list.stream().sorted(Comparator.comparing(StakeRangeNoVo::getLng).reversed()).collect(Collectors.toList());

11、Bigdecimal 类型累加

  BigDecimal totalServiceFee = list.stream().map(ChargingGunStreamVo::getTotalServiceFee).reduce(BigDecimal.ZERO, BigDecimal::add);

posted @ 2021-06-22 11:07  XuTingYin  阅读(87)  评论(0)    收藏  举报