List stream 数据处理

1、list转map

        //material_attrs name-code
        List<MaterialAttrsPO> materialAttrsPOS = materialAttrsService.queryPorscheImportMetadataAttrs();
        //字段转map
        Map<String, String> attrsMap = materialAttrsPOS.stream().collect(Collectors.toMap(MaterialAttrsPO::getName, MaterialAttrsPO::getCode));
        //attr_code list
        List<String> attrCodeList = new ArrayList<>(attrsMap.values());
        // material_attrs_options
        List<MaterialAttrsOptionsPO> attrsOptionsPOS = materialAttrsOptionsService.queryOptionsListByCodes(attrCodeList);
        // 以attrCode为key,该attrCode下所有选项值为value (groupingBy转map)
        Map<String, List<MaterialAttrsOptionsPO>> attrsOptionsAttrCodeMap = attrsOptionsPOS.stream()
                .collect(Collectors.groupingBy(MaterialAttrsOptionsPO::getAttrCode));    

2、字符串转list

Stream.of(source).collect(Collectors.toList());

3、数组转list

Arrays.stream(specificModel.split("/")).collect(Collectors.toList())

4、过滤空字符串和null值

List<String> titles = titles.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList());

5、对list里面元素做处理

// 去空格 s 可以匹配空格、制表符、换页符等空白字符的其中任意一个
List<String>  titles = titles.stream().map(str -> str.replaceAll("\s*","")).collect(Collectors.toList());

6、根据list里面元素对象的某属性做过滤

List<String> finalTitles = titles;
List<MaterialAttrsOptionsPO>  optionsList = optionsList.stream().filter(po -> po.getAttrCode().equals(code)
                    && finalTitles.contains(po.getTitle().replaceAll("\s*","")))
                    .collect(Collectors.toList());
原文地址:https://www.cnblogs.com/BobXie85/p/15512559.html