1. 程式人生 > 其它 >java List stream 操作

java List stream 操作

一、 Stream操作

1、精確匹配並獲取任意一個


Report report = reportList.stream().filter(item -> item.getReportNo().equals(mp4ReportNo)).findFirst().orElse(null);

2、精確匹配並獲取任意一個

 childs = childs.stream().map(child -> {
                List<String> pids = null;
                if (StringUtils.isNotEmpty(child.getpIds())) {
                    pids = new ArrayList<>(Arrays.asList(child.getpIds().split(",")));
                    if (!pids.contains(techniqueStation.getMid().toString())) {
                        pids.add(techniqueStation.getMid().toString());
                    }
                } else {
                    pids = new ArrayList<>();
                    pids.add(techniqueStation.getMid().toString());
                    child.setpIds(String.join(",", pids));
                }

                return child;

            }).collect(Collectors.toList());

3、排序

 fileInfos = fileInfos.stream().sorted(Comparator.comparing(FileInfo::getVersionNo).reversed()).collect(Collectors.toList());

4、獲取List中 bean的某一屬性的List

List<Long> fileInfoIds=reporttemplates.stream().map(Reporttemplate::getSystemFileId).collect(Collectors.toList());

testItemList = testItemList.stream().collect(

            Collectors.collectingAndThen(

                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TestItem::getMid))), ArrayList::new)

    );

5、 判斷是否存在

list.stream.filter(m->m.getName().equals("張三")).findAny().isPresent();

6、逗號拼接的字串轉List 或者其他的型別

  List<Long> orgIds = Arrays.stream(needPlanOrgs.split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());

7、List轉 陣列

int[] arr = list.stream().mapToInt(Integer::intValue).toArray();

8、兩個List 根據某個屬性求差集

list = list.stream().filter(m -> !modelInfos.stream().map(d -> d.getOfferModelId()).collect(Collectors.toList()).contains(m.getMid())).collect(Collectors.toList());