Java8 Stream 使用技巧

  • 排序
// 简单的排序
list.stream().sorted(Comparator.comparing(OrganizationVo::getOrgId).reversed()).collect(Collectors.toList());

// 多字段排序
list.stream().sorted(Comparator.comparing(OrganizationVo::getOrgId).thenComparing(OrganizationVo::getSort))
.collect(Collectors.toList());

// 字段处理后排序
list.stream().sorted(Comparator.comparing(OrganizationVo::getOrgId,Comparator.reverseOrder())).collect(Collectors.toList());

// 自定义比较器1
list.stream().sorted((o1, o2) -> Integer.parseInt(o2.getDeviceType()) -Integer.parseInt(o1.getDeviceType()))
.collect(Collectors.toList());

// 自定义比较器2
list.stream().sorted((o1, o2) -> ServiceImpl.getSort(o1).compareTo(NewsServiceImpl.getSort(o2)) <= 0 ? -1 : 1)
.collect(Collectors.toList());

public static Integer getSort(NewsDto dto) {
    // 自定义比较代码
    return Integer.parseInt(dto.getNewsId());
}
  • List to Map
Map<String, OrganizationVo> orgMap = orgList.stream()
.collect(Collectors.toMap(OrganizationVo::getOrgId, Function.identity(), (a, b) -> a));
  • List 降维
// List<List<Object>>  -> List<Object>
list.stream().map(e -> e.getList).flatMap(t-> t.stream()).collect(Collectors.toList());

// List<Map<Long,String>> -> List<Long>
List<Long> collect = list.stream()
            .map(Map::keySet)
            .collect(Collectors.collectingAndThen(Collectors.toList(),
                t -> t.stream().flatMap(Collection::stream).collect(Collectors.toList())));
  • List 去重
// 普通简单写法
Set<Object> set = Sets.newConcurrentHashSet();
List<OrganizationVo> resultList = 
list.stream().filter(vo -> set.add(vo.getOrgId())).collect(Collectors.toList());
// 函数式接口写法
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
    Set<Object> set = Sets.newConcurrentHashSet();
    return t -> set.add(keyExtractor.apply(t));
}

List<OrganizationVo> resultList= 
list.stream().filter(distinctByKey(vo -> vo.getOrgId())).collect(Collectors.toList());
  • List 分组
list.stream().collect(Collectors.groupingBy(OrganizationVo::getOrgId));
  • List分组后计数
Map<String, Long> collect = relatedList.stream()
.collect(Collectors.groupingBy(GroupProductRelationDto::getGroupId, Collectors.counting()));
  • List分组后取字段拼接
Map<String, String> collect = detailList.stream()
 .collect(Collectors.groupingBy(WorkOrderDetailDto::getOrgId, 
 Collectors.collectingAndThen(Collectors.toList(), t -> t.stream().map(WorkOrderDetailDto::getServiceName).collect(Collectors.joining(",")))));
  • List分组后根据某字段求和
// 处理spu库存 -> 根据productId 分组计算sku库存之和
Map<String, Integer> stockMap = oriSkuList.stream().collect(Collectors.groupingBy(ProductSkuDto::getProductId,
        Collectors.collectingAndThen(Collectors.toList(), t -> t.stream().mapToInt(ProductSkuDto::getSkuStock).sum())));

// 处理spu库存 -> 根据productId 分组 判断spu库存状态用
Map<String, List<Integer>> stockListMap = oriSkuList.stream().collect(Collectors.groupingBy(ProductSkuDto::getProductId,
        Collectors.collectingAndThen(Collectors.toList(), t -> t.stream().map(ProductSkuDto::getSkuStock).collect(Collectors.toList()))));
  • List分组后做处理
// List分组后 处理成 Map
Map<String, List<String>> collect2 = 
list.stream().collect(Collectors.groupingBy(GroupProductRelationDto::getBizId,
Collectors.collectingAndThen(Collectors.toList(), 
t -> t.stream().map(GroupProductRelationDto::getGroupId).collect(Collectors.toList()))));
// 效果
GroupProductRelationDto(groupId=0, groupIdList=null, bizId=1111, bizIdList=null)
GroupProductRelationDto(groupId=1, groupIdList=null, bizId=1111, bizIdList=null)
GroupProductRelationDto(groupId=2, groupIdList=null, bizId=1111, bizIdList=null)
GroupProductRelationDto(groupId=3, groupIdList=null, bizId=1111, bizIdList=null)
GroupProductRelationDto(groupId=5, groupIdList=null, bizId=222, bizIdList=null)
GroupProductRelationDto(groupId=6, groupIdList=null, bizId=222, bizIdList=null)
GroupProductRelationDto(groupId=7, groupIdList=null, bizId=222, bizIdList=null)
GroupProductRelationDto(groupId=8, groupIdList=null, bizId=222, bizIdList=null)

----------------------------

{"222":["5","6","7","8"],"1111":["0","1","2","3"]}
  • List求和
// Integer类型求和
List<Integer> list= Lists.newArrayList(1,2,3);
// 0是初始叠加值
Integer reduce = list.stream().reduce(0, (x, y) -> x = x + y);
System.out.println(reduce);
-------------------
6
// 方式二 
List<Integer> list = Lists.newArrayList(1,2,3);
int result2 = list.stream().mapToInt(t -> t).sum();
double result3 = list.stream().mapToDouble(t -> t).sum();
long result4 = list.stream().mapToLong(t -> t).sum();
System.out.println("int计算值:" + result2);
System.out.println("double计算值:" + result3);
System.out.println("long计算值:" + result4);
-------------------
int计算值:6
double计算值:6.0
long计算值:6
// BigDecimal类型求和
List<BigDecimal> list1 = Lists.newArrayList(BigDecimal.valueOf(2.87),BigDecimal.valueOf(3.555));
BigDecimal sum1 = list1.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
System.out.println(sum1);
-------------------
6.425

List<BigDecimal> list2 = Lists.newArrayList(new BigDecimal("2.87"),new BigDecimal("3.555"));
BigDecimal sum2 = list2.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
System.out.println(sum2);
-------------------
6.425
        
List<BigDecimal> list3 = Lists.newArrayList(new BigDecimal(2.87),new BigDecimal(3.555));
BigDecimal sum3 = list3.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
System.out.println(sum3);
-------------------
6.425000000000000266453525910037569701671600341796875

tips: BigDecimal对象创建应使用 BigDecimal(String val) 构造方法
或者 BigDecimal.valueOf(double val) 静态方法来创建对象.否则就会出现示例中的精度问题.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值