Java Stream实现:为List中重复的Student姓名拼接对应value后缀
重名学生字段拼接的实现方案
实现规则说明
- 仅对学生列表中出现次数大于1的重名对象,将
name与value用下划线拼接为name_value格式字符串 - 对不存在重名的学生,直接输出原
name字段值即可
完整实现代码
// 需导入的依赖类 import java.util.*; import java.util.stream.Collectors; // Student模型类 class Student { private String name; private String value; public Student(String name, String value) { this.name = name; this.value = value; } // 提供字段的getter方法供流操作读取属性 public String getName() { return name; } public String getValue() { return value; } } public class NewTes { public static void main(String[] args) { Student s1 = new Student("xyz", "a1"); Student s2 = new Student("abc", "a2"); Student s3 = new Student("xyz", "a3"); List<Student> studentList = new ArrayList<>(); studentList.add(s1); studentList.add(s2); studentList.add(s3); // 一次性统计所有姓名的出现频次,替代原方案反复全量遍历算重复值的逻辑 Map<String, Long> nameFrequencyMap = studentList.stream() .collect(Collectors.groupingBy(Student::getName, Collectors.counting())); // 提取所有重复出现的姓名集合,和原代码筛选得到的result集合等价 Set<String> duplicateNameSet = nameFrequencyMap.entrySet().stream() .filter(entry -> entry.getValue() > 1) .map(Map.Entry::getKey) .collect(Collectors.toSet()); // 遍历生成最终结果列表 List<String> outputList = studentList.stream() .map(student -> { if (duplicateNameSet.contains(student.getName())) { // 重名对象执行拼接逻辑 return student.getName() + "_" + student.getValue(); } // 非重名学生直接返回原姓名 return student.getName(); }) .collect(Collectors.toList()); // 输出结果与预期一致:[xyz_a1, abc, xyz_a3] System.out.println(outputList); } }
原有代码的卡点问题说明
之前尝试编写的流式逻辑存在两处明显问题,导致无法运行得到正确结果:
- 逻辑截断不完整:提前将
Student对象map为纯姓名字符串后,就丢失了原对象的value属性,拼接时拿不到后缀字段- 分支覆盖不全:三元判断逻辑没有闭合,也没有处理“非重名学生直接返回原name”的场景
方案优化点
- 原代码使用
Collections.frequency筛选重复姓名时,每遍历一个元素都会对全量姓名列表做一次全量扫描,列表数据量越大性能损耗越高;替换为一次遍历分组统计频次的逻辑后,整体时间复杂度从O(n²)降到O(n) - 全程保留完整的
Student对象实例,避免提前转型丢失业务字段,后续需要调整拼接规则时也不需要重构前面的流逻辑
内容的提问来源于stack exchange,提问作者Bhanu
相关产品推荐
相关产品推荐

