Java中Stream使用方式

本文介绍了JavaStreamAPI的常见用法,包括使用map进行转换,流的分页技巧,排序方法,toMap函数的应用,数值求和,属性提取为集合或数组,去重操作,过滤元素,以及并发流的使用。同时展示了如何处理BigDecimal对象并避免空指针异常。
摘要由CSDN通过智能技术生成
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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值