总结一下常见的一些stream流表达式的用法:
目录
Collectors
Collectors.toMap():将属性映射到Map
Map<Long, String> map = list.stream().collect(Collectors.toMap(x->x.getId(), y->y.getName()));
map
map() 获取单一属性List<>
List<String> idList = ObjectList.stream.map(Object::getId).collect(Collectors.toList());
filter
filter() 用于通过设置的条件过滤出元素。
permissionList.stream()
.filter(permission -> permission.getValue()!=null)
.map(permission ->new SimpleGrantedAuthority(permission.getValue()))
.collect(Collectors.toList());
distinct
distinct() 去重 distinct()是Java 8 中 Stream 提供的方法,返回的是由该流中不同元素组成的流。distinct()使用 hashCode() 和 eqauls() 方法来获取不同的元素。
因此,需要去重的类必须实现 hashCode() 和 equals() 方法。换句话讲,我们可以通过重写定制的 hashCode() 和 equals() 方法来达到某些特殊需求的去重。
groupingBy 分组
Collectors.groupingBy() 分组:
Map map = objectList.stream()
.collect(Collectors.groupingBy(m -> refleshUtils.getProperty(m, filed), Collectors.toList()));
collectingAndThen去重
Collectors.collectingAndThen()去重
List list = objectList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(mqBody::getPolicyOwner))), ArrayList::new)
);
sort排序
sort() 排序
/*正序*/
List<User> Asclist = userList.stream().sorted(Comparator.comparingInt(User::getId)).collect(Collectors.toList());
/*倒序*/
List<User> DescList = userList.stream().sorted(Comparator.comparingInt(User::getId).reversed()).collect(Collectors.toList());
limit skip限流
limit() 限制数据量
mqDataTimes = mqDataTimes.stream().limit(limit).collect(Collectors.toList());
skip(lang n) 是一个跳过前 n 个元素的中间流操作
mqDataTimes = mqDataTimes.stream().skip(skip).collect(Collectors.toList());
skip(lang n) 是一个跳过前 n 个元素的中间流操作
limit() 限制数据量
这两个方法都是截取了流。但是它们有一些区别 skip 操作必须时刻监测流中元素的状态。才能判断是否需要丢弃。所以 skip 属于状态操作。
而 limit 只关心截取的是不是其参数 maxsize (最大区间值),其它毫不关心。一旦达到就立马中断操作返回流。所以 limit 属于一个中断操作。
count统计
count() 统计
long count = mqDataTimes.stream().count();
stream流求和求最大值平均值
List<Person> personList = new ArrayList<>();
personList.add(new Person("xiaoming", 22, "男"));
personList.add(new Person("xiaoming", 21, "男"));
personList.add(new Person("duwea1", 13, "男"));
personList.add(new Person("ewwwea1", 34, "男"));
List<Integer>value = personList.stream().map(Person::getAge).collect(Collectors.toList());
Integer max = value.stream().max((a,b)->a-b).get();
Integer min = value.stream().min((a,b)->a-b).get();
double av = value.stream().mapToInt(Integer::intValue).average().getAsDouble();
Integer sum = value.stream().mapToInt(Integer::intValue).sum();
System.out.println(max);
System.out.println(min);
System.out.println(av);
System.out.println(sum);