常用Stream API示例

发布时间 2023-10-10 13:24:02作者: mindSucker

1.flatMap

    将多个集合压平为一个集合

List<Long> siteIdList = routeLines.stream()
		.flatMap(routeLine -> Stream.of(routeLine.getSubLineFSiteId(), routeLine.getSubLineTSiteId()))
		.distinct()
		.collect(Collectors.toList());

2. Collectors.toMap()


        List<BaseWarehouse> warehouseList = ClientUtil.request(() -> vwmsClient.batchQueryWarehouse(new BaseWarehouseQueryForm()));

        Map<String, BaseWarehouse> fenceNoWarehouseMap = warehouseList.stream()
                .filter(w -> CollectionUtils.isNotEmpty(w.getFenceNoList()))
                .flatMap(w -> w.getFenceNoList().stream().map(a -> new SimpleEntry<String, BaseWarehouse>(a, w)))
                .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue, (c, d) -> c));