lambad和stream流企业固定搭配
1. 遍历/批量处理:forEach
业务场景:查出了一堆用户,需要批量往里面塞个默认状态,或者批量打印日志。 固定搭配:集合.forEach(对象 -> 操作逻辑)
// 传统写法:for循环
for (User user : userList) {
System.out.println(user.getName());
}
// 企业流写法:直接点 forEach
userList.forEach(user -> System.out.println(user.getName()));
// 极简缩写(结合 ::)
userList.forEach(System.out::println);
2. 过滤/筛选:filter
业务场景:从所有用户中,只挑出年龄大于 18 岁的人。 固定搭配:集合.stream().filter(对象 -> 条件判断).collect(Collectors.toList())
List<User> adults = userList.stream()
.filter(user -> user.getAge() > 18) // 条件为 true 的保留,false 的丢弃
.collect(Collectors.toList()); // 【固定结尾】把流重新打包成 List
3. 提取某一列/对象转换:map ⭐️(用得最多)
业务场景 A(提取单列):我不需要整个 User 对象,我只要所有人的名字列表。 业务场景 B(实体类转 Resp):把 User 对象转换成 UserResp 返回给前端。 固定搭配:集合.stream().map(对象 -> 转换逻辑).collect(Collectors.toList())
// 场景A:只要名字
List<String> names = userList.stream()
.map(user -> user.getName()) // 把 User 变成了 String
.collect(Collectors.toList());
// 场景A极简缩写(结合 ::)
List<String> names = userList.stream()
.map(User::getName)
.collect(Collectors.toList());
// 场景B:实体转Resp(结合你之前问的)
List<UserResp> respList = userList.stream()
.map(user -> {
UserResp resp = new UserResp();
resp.setName(user.getName());
return resp;
})
.collect(Collectors.toList());
4. 排序:sorted
业务场景:按用户的年龄从小到大(升序)排,或者按创建时间从晚到早(降序)排。 固定搭配:集合.stream().sorted(Comparator.comparing(对象::get字段)).collect(...)
// 升序(从小到大)
List<User> sortedList = userList.stream()
.sorted(Comparator.comparing(User::getAge))
.collect(Collectors.toList());
// 降序(从大到小,在后面加个 .reversed())
List<User> sortedListDesc = userList.stream()
.sorted(Comparator.comparing(User::getAge).reversed())
.collect(Collectors.toList());
5. 判断是否包含/匹配:anyMatch
业务场景:检查这批用户里,有没有名字叫“张三”的。不需要查出具体数据,只要一个 true/false。 固定搭配:集合.stream().anyMatch(对象 -> 条件)
boolean hasZhangSan = userList.stream()
.anyMatch(user -> "张三".equals(user.getName()));
// 只要找到一个匹配的,立刻返回 true,后面不再执行了(短路)
6. 分组:groupingBy ⭐️(极其常用)
业务场景:把用户按照部门ID(或者性别、状态)分组,变成一个 Map。以前要写一大堆 for 循环 if 判断,现在一行搞定。 固定搭配:集合.stream().collect(Collectors.groupingBy(对象::get分组依据))
// 按照性别分组
// 结果:Map<Integer, List<User>> (Key是性别1/2,Value是对应的用户列表)
Map<Integer, List<User>> genderMap = userList.stream()
.collect(Collectors.groupingBy(User::getGender));
7. List 转 Map:toMap ⭐️(新人最容易踩坑的地方)
业务场景:把 List 转成 Map,方便后面用 ID 快速查找对象,不用每次都 for 循环。 固定搭配:集合.stream().collect(Collectors.toMap(对象::getKey, 对象 -> 对象本身))
// 把 List<User> 转成 Map<用户ID, User对象>
Map<Long, User> userMap = userList.stream()
// 【固定写法】第一个参数是Key(User::getId),第二个参数是Value(u -> u 表示对象本身)
.collect(Collectors.toMap(User::getId, user -> user));
// ⚠️企业防坑写法:如果你的List里有两个相同的ID,上面的代码会报错!
// 所以企业里通常会加上第三个参数,表示遇到相同Key时保留哪一个:
Map<Long, User> safeUserMap = userList.stream()
.collect(Collectors.toMap(User::getId, user -> user, (oldKey, newKey) -> oldKey));
- 开头:但凡想用流,先无脑敲
.stream() - 车间:
filter筛选、map改造、sorted排队 - 结尾:要变回 List 就
.collect(Collectors.toList()),要变 Map 就.collect(Collectors.toMap(...)),只要判断就.anyMatch(...)
更多推荐
所有评论(0)