Java8新特性stream装逼必备操作(持续更新)

废话少说 直接开装!!!

Stream 的distinct()方法(需要重新equals() 以及 hashCode())

 List<PenBean> newPenBeanList = penBeanList.stream().distinct().collect(Collectors.toList());

根据 List 中 Object 某个属性去重

//根据user的account属性去重
List<User> list =users.stream().collect( Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getAccount()))),ArrayList::new));

## 获取集合第一个对象 没有就返回为null;

```bash
list.stream().findFirst().orElse(null);

获取list中对象的属性的所有值

//获取PmsProductCategory集合里面PmsProductCategory的id
List<Long> cid = categories.stream().map(PmsProductCategory::getId).collect(Collectors.toList());

list按照对象的某个属性分组

//按照pmsProduct的productCategoryId进行分组
Map<Long, List<PmsProduct>> productMap = pmsProducts.stream().collect(Collectors.groupingBy(PmsProduct::getProductCategoryId));
/**
 * String字符串转成List<Long>数据格式
 * String str = "1,2,3,4,5,6" -> List<Long> listLong [1,2,3,4,5,6];
 *
 * @param strArr
 * @return
 */
private List<Long> stringToLongList(String strArr) {
    
    
    return Arrays.stream(strArr.split(","))
                    .map(s -> Long.parseLong(s.trim()))
                    .collect(Collectors.toList());
}

将Long类型集合转成String类型集合

Set<String> skuStr= skuIds.stream().map(String::valueOf).collect(Collectors.toSet());

根据对象的某个属性进行排序

list.stream().sorted(Comparator.comparing(Product::getId).reversed()).collect(Collectors.toList());

获取对象某个属性的集合

List<Long> orderId = omsOrderPage.getRecords().stream().map(OmsOrder::getId).collect(Collectors.toList());

猜你喜欢

转载自blog.csdn.net/weixin_45528650/article/details/109153245