Java中如何将List内相同ID对应的多条日期记录合并为一条?
实现方案
你只需要在原有合并得到newList的基础上,按ID分组聚合所有时间即可,Java Stream可以直接实现该需求,步骤如下:
第一步:调整Logs类结构(推荐)
Java类不支持定义多个同名字段,因此建议把原Logs类的单个time字段调整为时间集合,示例结构:
class Logs { private String id; // 替换原有的单个time字段为集合,存储该ID对应的所有日期 private List<String> times; // 全参构造器 public Logs(String id, List<String> times) { this.id = id; this.times = times; } // 重写toString方法,输出你需要的多time格式 @Override public String toString() { StringBuilder sb = new StringBuilder("{id='").append(id).append("'"); times.forEach(time -> sb.append(", time=").append(time)); sb.append("}"); return sb.toString(); } // 原有getter、setter方法自行补充 }
第二步:流式处理合并相同ID的记录
在原有得到newList之后,新增如下分组转换代码即可:
List<Logs> mergedLogs = newList.stream() // 按ID分组,收集对应ID的所有time字段 .collect(Collectors.groupingBy( Logs::getId, Collectors.mapping(Logs::getTime, Collectors.toList()) )) // 把分组后的Map转为目标Logs集合 .entrySet() .stream() .map(entry -> new Logs(entry.getKey(), entry.getValue())) .collect(Collectors.toList()); // 打印验证,输出格式和你期望的结果完全一致 System.out.println(mergedLogs);
如果不能修改原有Logs类结构
如果必须保留原有Logs类的单time字段结构,可以通过Collectors.toMap的合并函数自定义拼接逻辑,示例(以拼接time属性到字符串为例):
List<Logs> mergedLogs = new ArrayList<>(newList.stream() .collect(Collectors.toMap( Logs::getId, log -> log, (oldLog, newLog) -> { // 自定义合并逻辑,把新log的time追加到老log的time字段后 oldLog.setTime(oldLog.getTime() + ", time=" + newLog.getTime()); return oldLog; } )) .values());
这种方式不需要改类结构,但time字段会变成拼接后的字符串,仅适合做展示用,不适合后续逻辑处理。
内容的提问来源于stack exchange,提问作者Taras
相关产品推荐
相关产品推荐

