collection.stream用法
stream流集几乎可以完成对集合的任意操作,映射、去重、分组、排序、过滤等
1.元素转换(映射) map
例1:
List<SalesOrderProduct> salesOrderProductList;
List<ProductItemReq> items = salesOrderProductList().stream()
.map(p -> {
ProductItemReq itemReq = new ProductItemReq();
itemReq.setProductItemId(p.getProductItemId());
itemReq.setQuantity(p.getQuantity().intValue());
itemReq.setVariantId(p.getVariantId());
return itemReq;
}).collect(Collectors.toList());
例2:
List<AbstractDomain> forUpdateList;
List<Integer> collect = forUpdateList.stream().map(
AbstractDomain::getId).collect(
Collectors.toList());
或者
List<Integer> collect1 = forUpdateList.stream().map(
d -> d.getId()).collect(
Collectors.toList());
2.去重 distinct
List<String> ids = products.stream().map(p -> p.getBusinessId()).distinct().collect(Collectors.toList());
//多个商家需要拆单
if (ids.size() == 1) {
return ids.get(0);
}
3. 数组分组 groupby
List<OrderSplitItemReq> paramSplitItems = new ArrayList<>();
Map<String, List<OrderSplitItemReq>> splitProductMap = paramSplitItems.stream()
.collect(Collectors.groupingBy(OrderSplitItemReq::getProductItemId));
4. stream中的元素转map Collectors.toMap
List<ProductVariantExt> productVariantExts = productVariantService.queryList(qryVariantDto);
Map<String, ProductVariantExt> variantMap = productVariantExts.stream().collect(Collectors.toMap(ProductVariantExt::getVariantId, Function.identity()));
5. 排序 sorted
List<CarOwnerRepurchantRights> sortedList = existsRights.stream().sorted(Comparator.comparing(CarOwnerRepurchantRights::getCreatedAt)).collect(Collectors.toList());
6.过滤 filter
//未配置业务线活动
List<String> tips = new ArrayList<>();
List<CouponActivityExtDto> withoutBusinessActivityList = activityList.stream().filter(x -> StringUtils.isEmpty(x.getBusinessCode())).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(withoutBusinessActivityList)) {
withoutBusinessActivityList.stream().forEach(x -> {
tips.add(x.getCouponActivityId() + x.getTitle() + "成本方未配置");
});
}
7.Function.identity()
Function.identity()返回一个输出跟输入一样的Lambda表达式对象,等价于形如t -> t形式的Lambda表达式
Stream<String> stream = Stream.of("zhao", "qian", "sun", "li");
Map<String, Integer> map = stream.collect(Collectors.toMap(Function.identity(), String::length));
System.out.println(map);
输出: {qian=4, zhao=4, li=2, sun=3}
Function.identity() 即输入的love等字符串作为map的key, 字符串的长度作为map的值
8.map和flatMap的区别
两者都用于映射
map直接映射,flatMap整合映射
比如:
// map函数单纯对元素进行映射
List<String> list = new ArrayList<>();
list.stream().map(str-> str+";")
.collect(Collectors.toList());
// map函数将List<String>映射成 List<List>
List<List> mapList = list.stream().map(str -> {
List list1 = new ArrayList<String>();
list1.add(str);
return list1;
}).collect(Collectors.toList());
// flatMap元素映射整合过程List<String> -> List<List> -> List<String>
// flatMap将 List的流 整合成 String
List<String> flatMapList = list.stream().flatMap(item -> {
List<String> list2 = new ArrayList<>();
list2.add(item);
return list2.stream();
}).collect(Collectors.toList());