最近发现这个Stream用的还是挺多的,基础语法掌握了,但是遇到实际场景的时候,又需要浪费很多时间才能写出来,所以对常用场景的写法进行总结,方便真实场景中快速应用。
另外关于基础语法和遇到的错误,可以参看我的其他文章
基础语法参考
Java8新特性:HashMap优化、lambda、Stream等新特性详解
遇到问题及解决参考
这个文章访问量是真多,应该这个错比较常见,大家通过搜索引擎搜到了它
Java8-Stream: no instance(s) of type variable(s) R exist so that void conforms to R
我们使用Stream主要是替换臃肿的for循环,对集合进行各种sao操作
主要有如下几种场景:
1、group by (分组)
2、order by (排序)
3、where (筛选)
4、distinct (去重)
5、appLy (根据某个属性进行各种操作)
6、提取某个属性为列表
根据性别进行分组
userList.stream()
.collect(Collectors.groupingBy(User::getSex));
复制代码
按照用户年龄进行排序(升序/降序)并且取top3
userList.stream()
.sorted(Comparator.comparing(User::getAge).reversed())
.limit(3)
.collect(Collectors.toList());
复制代码
获得某个属性最大/最小的对象
// 最小
Optional min = userList.stream()
.min(Comparator.comparing(User::getAge));
// 最大
Optional max = userList.stream()
.max(Comparator.comparing(User::getAge));
// 获得对象
// 这里会有'Optional.get()' without 'isPresent()' check的提示,可以换为User user = min.orElse(null);
User user = min.get();
复制代码
筛选年龄小于30岁的用户
userList.stream()
.filter(e -> e.getAge() < 30)
.collect(Collectors.toList());
复制代码
选择用户年龄> 20 且性别为 男性的(sex=1)
userList.stream()
.filter(u -> u.getAge() > 20 && u.getSex() == 1)
.collect(Collectors.toList());
复制代码
查询第一个姓名叫"李华"的用户
userList.stream()
.filter(u -> u.getName().equals("小明"))
.findFirst().orElse(ll);
复制代码
筛选掉name为null的数据
userList.stream()
.filter(u -> u.getName() != null)
.collect(Collectors.toList());
复制代码
获取所有的用户名,并去重
userList.stream()
.map(User::getName)
.distinct()
.collect(Collectors.toList());
复制代码
根据某字段去重
memberListAll.stream()
.collect(Collectors.collectingAndThen(
Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(WorkWxUserInfoVO :: getUserid))), ArrayList::new)
);
复制代码
根据某字段去重(不乱序)
static Predicate distinctByKey(Function super T, ?> keyExtractor) {
Map
list.stream().filter(distinctByKey(b -> b.getName())).collect(Collectors.toList());
复制代码
给某个属性批量赋值
userList.forEach(e -> {
e.setName("hello");
});
复制代码
对某个字段进行处理
userList.stream()
.map(user -> {user.setName(user.getName().replaceAll("\u0000", "")); return user;})
.collect(Collectors.toList());
复制代码
根据某个字段获得对象
List userList = userIds.stream()
.map(id -> {
User user = userService.getUserById(id);
return user;
})
.collect(Collectors.toList());
复制代码
提取单个属性:获取所有的用户名,并去重
userList.stream()
.map(User::getName)
.distinct()
.collect(Collectors.toList());
复制代码
提取多个属性:将menuId和menuName组成map(menuId唯一)
userList.stream()
.collect(Collectors.toMap(User::getMenuId, User::getMenuName)));
复制代码
提取多个属性:将menuId和menuName组成map(menuId不唯一)
userList
//去重
.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(User :: getMenuId))), ArrayList::new))
//转map
.stream().collect(Collectors.toMap(User::getMenuId, User::getMenuName)));
复制代码
计算某个属性的和
Long allCount = userList.stream().mapToLong(User::getScore).sum();