lambad和stream流企业固定搭配

📅 2026/7/7 9:14:23
lambad和stream流企业固定搭配
1. 遍历/批量处理forEach业务场景查出了一堆用户需要批量往里面塞个默认状态或者批量打印日志。固定搭配集合.forEach(对象 - 操作逻辑)// 传统写法for循环for (User user : userList) {System.out.println(user.getName());}// 企业流写法直接点 forEachuserList.forEach(user - System.out.println(user.getName()));// 极简缩写结合 ::userList.forEach(System.out::println);2. 过滤/筛选filter业务场景从所有用户中只挑出年龄大于 18 岁的人。固定搭配集合.stream().filter(对象 - 条件判断).collect(Collectors.toList())ListUser adults userList.stream().filter(user - user.getAge() 18) // 条件为 true 的保留false 的丢弃.collect(Collectors.toList()); // 【固定结尾】把流重新打包成 List3. 提取某一列/对象转换map⭐️用得最多业务场景 A提取单列我不需要整个 User 对象我只要所有人的名字列表。业务场景 B实体类转 Resp把 User 对象转换成 UserResp 返回给前端。固定搭配集合.stream().map(对象 - 转换逻辑).collect(Collectors.toList())// 场景A只要名字ListString names userList.stream().map(user - user.getName()) // 把 User 变成了 String.collect(Collectors.toList());// 场景A极简缩写结合 ::ListString names userList.stream().map(User::getName).collect(Collectors.toList());// 场景B实体转Resp结合你之前问的ListUserResp 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(...)// 升序从小到大ListUser sortedList userList.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());// 降序从大到小在后面加个 .reversed()ListUser 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分组依据))// 按照性别分组// 结果MapInteger, ListUser (Key是性别1/2Value是对应的用户列表)MapInteger, ListUser genderMap userList.stream().collect(Collectors.groupingBy(User::getGender));7. List 转 MaptoMap⭐️新人最容易踩坑的地方业务场景把 List 转成 Map方便后面用 ID 快速查找对象不用每次都 for 循环。固定搭配集合.stream().collect(Collectors.toMap(对象::getKey, 对象 - 对象本身))// 把 ListUser 转成 Map用户ID, User对象MapLong, User userMap userList.stream()// 【固定写法】第一个参数是Key(User::getId)第二个参数是Value(u - u 表示对象本身).collect(Collectors.toMap(User::getId, user - user));// ⚠️企业防坑写法如果你的List里有两个相同的ID上面的代码会报错// 所以企业里通常会加上第三个参数表示遇到相同Key时保留哪一个MapLong, 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(...)