Java 8 Stream 流的实用操作详解
基于条件的排序处理
利用 Stream 的 sorted() 方法可以灵活实现对象列表的排序。例如,对自定义对象按某个字段升序排列,并以特定分隔符拼接结果:
private String formatCodeSequence(List<CAutoDistributionInfo> dataList) {
return dataList.stream()
.sorted(Comparator.comparing(CAutoDistributionInfo::getCode))
.map(info -> String.valueOf(info.getCode()))
.collect(Collectors.joining("|")) + "|";
}
当需要按照非自然顺序排序时,可结合映射表进行自定义比较逻辑。比如根据预设优先级对站点编码排序:
public List<UserStationEntity> fetchSortedStations() {
Map<String, Integer> priorityMap = new HashMap<>();
priorityMap.put("cc.dcc", 1);
priorityMap.put("cc.coperation", 2);
List<UserStationEntity> rawList = userStationMapper.selectList(null);
return rawList.stream()
.sorted(Comparator.comparing(
UserStationEntity::getStationCode,
(code1, code2) -> priorityMap.getOrDefault(code1, Integer.MAX_VALUE)
- priorityMap.getOrDefault(code2, Integer.MAX_VALUE)
).thenComparing(UserStationEntity::getCreateUsername))
.collect(Collectors.toList());
}
对于嵌套属性的排序,也可以通过链式调用完成。如下例中先按扩展模型中的订单状态排序,再提取报价状态:
List<Integer> statusList = offerCarPage.stream()
.sorted(Comparator.comparing(
OfferCarResourceModel::getExtendModel,
Comparator.comparingInt(ext -> Optional.ofNullable(ext.getOrderStatus()).orElse(0))
))
.map(model -> Integer.parseInt(model.getOfferStatus()))
.collect(Collectors.toList());
将 List 转换为 Map 结构
使用 Collectors.toMap() 可将集合快速转换为键值对形式。
- 键和值均为实体属性:
Map<String, String> idToNameMap = userList.stream()
.collect(Collectors.toMap(User::getId, User::getName));
- 键为属性,值为整个对象(显式 lambda):
Map<String, User> idToObjectMap = userList.stream()
.collect(Collectors.toMap(User::getId, u -> u));
- 使用
Function.identity()简化写法:
Map<String, User> idToSelfMap = userList.stream()
.collect(Collectors.toMap(User::getId, Function.identity()));
- 处理重复 key 的情况,保留后出现的元素:
Map<String, User> deduplicatedMap = userList.stream()
.collect(Collectors.toMap(
User::getId,
Function.identity(),
(existing, replacement) -> replacement // 冲突时覆盖旧值
));
分组操作:groupingBy 与 partitioningBy
根据某一属性对数据进行分类是常见需求。Collectors.groupingBy() 提供了便捷方式。
class Student {
private String grade;
private String classNumber;
private String name;
private int age;
private int mathScores;
private int chainessScores;
}
按班级编号分组学生列表:
Map<String, List<Student>> groupedByClass = students.stream()
.collect(Collectors.groupingBy(Student::getClassNumber));
System.out.println(JSON.toJSONString(groupedByClass));
构建树形结构数据
在处理具有父子关系的数据时,可通过流操作组装成层级结构。
private DetectResultResModel buildResultModel(DetectResultRes source) {
DetectResultResModel model = new DetectResultResModel();
BeanUtils.copyProperties(source, model);
String fileIds = source.getFileIds();
if (StringUtils.isNotBlank(fileIds)) {
List<String> idList = Arrays.asList(fileIds.split(","));
model.setFiles(fileFeignService.queryFileVisitUrl(idList, null, 900L, "1"));
}
return model;
}
将扁平列表转换为带子节点的树状结构:
@PostMapping("/selectDetectResultRes")
public ResultModel buildHierarchicalResults(@RequestBody DetectResultReq req) {
PageListModel<DetectResultRes> pageData = detectClient.selectDetectResultRes(req);
List<DetectResultResModel> flatList = pageData.getList().stream()
.map(this::buildResultModel)
.collect(Collectors.toList());
// 按父ID分组
Map<Integer, List<DetectResultResModel>> parentGroup = flatList.stream()
.collect(Collectors.groupingBy(DetectResultResModel::getParentId));
// 设置子节点
flatList.forEach(item -> item.setChildren(parentGroup.get(item.getDetectBaseId())));
return ResponseDataUtil.success(flatList.get(0));
}
集合间的差集计算
从一个集合中排除另一个集合包含的元素,常用于数据过滤。
List<GoodModel> modelList = getGoodModelList();
List<GoodVo> voList = getGoodVoList();
// 过滤掉 voList 中 number 在 modelList 中已存在的项
List<GoodVo> filteredVoList = voList.stream()
.filter(vo -> !modelList.stream()
.map(GoodModel::getNumber)
.collect(Collectors.toList())
.contains(vo.getNumber()))
.collect(Collectors.toList());
属性提取与去重
提取单一字段并去重:
List<String> uniqueNames = userList.stream()
.map(User::getName)
.distinct()
.collect(Collectors.toList());
提取多个属性组成 Map(假设 menuId 唯一):
Map<Long, String> menuMapping = userList.stream()
.collect(Collectors.toMap(User::getMenuId, User::getMenuName));
若 menuId 不唯一,需先去重后再转 Map:
Map<Long, String> dedupedMenuMap = userList.stream()
.collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User::getMenuId))),
ArrayList::new
)).stream()
.collect(Collectors.toMap(User::getMenuId, User::getMenuName));
查找与条件判断
使用 findFirst() 配合 Optional 安全获取匹配项:
Optional<UserReq> found = toAssignUserList.stream()
.filter(user -> user.getUserId().equals(lastClueAssignLogEntity.getAdId()))
.findFirst();
if (found.isPresent()) {
toIndex = toAssignUserList.lastIndexOf(found.get()) + 1;
}
移除满足条件的元素
结合 removeIf 实现动态删除:
showList.forEach(config ->
list.removeIf(item -> item.getId().equals(config.getColumnId()))
);