废话少说 直接开装!!!
Stream 的distinct()方法(需要重新equals() 以及 hashCode())
List<PenBean> newPenBeanList = penBeanList.stream().distinct().collect(Collectors.toList());
filter筛选
筛选大于年龄18的用户
users.stream().filter(e -> e.getAge > 18).collect(Collectors.toList());
limit返回指定集合个数
users.stream().limit(返回个数).collect(Collectors.toList());
skip跳过流中的元素
- 通过skip方法跳过流中的元素,skip的参数值必须>=0,否则将会抛出异常
users.stream().skip(跳过个数).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;
list.stream().findFirst().orElse(null);
map流映射 获取list中对象的属性的所有值
//获取PmsProductCategory集合里面PmsProductCategory的id
List<Long> cid = categories.stream().map(PmsProductCategory::getId).collect(Collectors.toList());
元素匹配
allMatch匹配所有
- 匹配categories集合中i所有d大于10就是匹配成功
categories.stream().allMatch(e->e.getId>10);
anyMatch匹配其中一个
- categories集合有一个id大于12算匹配成功
categories.stream().anyMatch(e -> e.Id() > 12);
noneMatch全部不匹配
- categories集合没有一个id大于12 算匹配成功
categories.stream().noneMatch(e -> e.Id() > 12);
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());
map用法
将String[] 转为List
String[] str={"1","2","3"};
List<Integer> collect = Arrays.stream(str).map(Integer::valueOf).collect(Collectors.toList());
System.out.println(collect);
获取对象某个属性的集合
List<Long> orderId = omsOrderPage.getRecords().stream().map(OmsOrder::getId).collect(Collectors.toList());
reduce 将流中的元素组合起来
//对list的rebateAmount进行求和
BigDecimal sumPoint = list.stream().map(TeamItem::getRebateAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
-
reduce接受两个参数,一个初始值这里是0,一个BinaryOperator accumulator
来将两个元素结合起来产生一个新值, -
另外reduce方法还有一个没有初始化值的重载方法
统计流中元素个数
- 通过count
Long result = list.stream().count();
- 通过counting
Long result = list.stream().collect(counting());
counting统计元素个数的方法在与collect联合使用的时候特别有用