1.stream中map的用法
List<SearchAttr> searchAttrList = attrList.stream().map(baseAttrinfo -> {
SearchAttr searchAttr = new SearchAttr();
return searchAttr;
}).collect(Collectors.toList());
List<String> searchAttrList =list.stream().map(String::length).collect(Collectors.toList());;
2.Stream中分页技巧和数据总数
// codeUseList:处理后的所有符合条件的数据(list)
// 组装返回结果对象 list:当前页数据列表 total:数据总数
dataMap.put("list", codeUseList.stream().skip((focusDetailDTO.getPage() - 1) * focusDetailDTO.getSize())
.limit(focusDetailDTO.getSize()).collect(Collectors.toList()));
dataMap.put("total", codeUseList.size());
3. Stream sorted() 排序示例
下面代码以自然序排序一个list
list.stream().sorted()
自然序逆序元素,使用Comparator 提供的reverseOrder() 方法
list.stream().sorted(Comparator.reverseOrder())
使用Comparator 来排序一个list
list.stream().sorted(Comparator.comparing(Student::getAge))
把上面的元素逆序
list.stream().sorted(Comparator.comparing(Student::getAge).reversed())
4.Stream中toMap()使用实例
// 循环遍历当前购物车集合,放入缓存,同时将skuPrice 赋值
Map<Long, CartInfo> infoMap = list.stream().map(cartInfo -> {
// 查询价格
BigDecimal skuPrice = productFeignClient.getSkuPrice(cartInfo.getSkuId());
// 实时出来的价格赋值
cartInfo.setSkuPrice(skuPrice);
// 放入缓存中
// redisTemplate.opsForHash().put(cartKey, cartInfo.getSkuId(), cartInfo);
return cartInfo;
}).collect(Collectors.toMap(CartInfo::getSkuId, o -> o)); // toMap 第一个时Key,第二个是Value
redisTemplate.opsForHash().putAll(cartKey,infoMap);
5.stream中某值求和sum()
int total = list.stream().mapToInt(User::getAge).sum();
int sum = list.stream().mapToInt(Integer::intValue).sum();
6.stream中集合单独取出对象中一个属性成为集合或数组
// 集合
List<DictEntity> dictEntityList = dictService.findByType(6);
//取出属性为集合
List<String> stateNameList = dictEntityList.stream().map(DictEntity::getName).collect(Collectors.toList());
//取出属性为数组
Long[] ids = dictEntityList.stream().map(DictEntity::getId).toArray(Long[]::new);
//集合去重
dictEntityList.stream().distinct().collect(Collectors.toList());
7.stream中集合去重和计数
long count = list.stream().distinct().count();
8.stream中过滤元素
Stream<String> stream = list.stream().filter(element -> element.contains("王"));
9.并发流
调用 parallelStream() 方法创建并发流,默认使用的是 ForkJoinPool.commonPool()线程池。
List<Long> aList = new ArrayList<>();
Stream<Long> parallelStream = aList.parallelStream();
10.stream对BigDecimal的操作
要加过滤条件,可能出现空指针错误
BigDecimal totalAmount = hzPropertyList.stream()
.filter(item -> item.getAmount() != null)
.map(HzProperty::getAmount)
.reduce(BigDecimal.ZERO, BigDecimal::add);