如何合并集合中重复城市的zip code,去重后合并多邮政编码为单条目
实现方案
前置实体定义
首先假设你的城市邮编实体类结构如下,可根据你实际的字段名调整对应逻辑:
import lombok.Data; // 如未使用Lombok,自行补充getter、setter和构造方法即可 @Data public class CityZip { private String city; private String zipCode; public CityZip(String city, String zipCode) { this.city = city; this.zipCode = zipCode; } }
Stream流实现
用Java Stream的分组收集器直接完成分组、邮编拼接、转换回实体的全流程:
import java.util.List; import java.util.stream.Collectors; public class MergeTest { public static void main(String[] args) { // 模拟原始数据集合,替换为你自己的数据集即可 List<CityZip> originalList = List.of( new CityZip("madrid", "19"), new CityZip("madrid", "28"), new CityZip("barcelona", "08"), new CityZip("valencia", "46") ); // 核心合并逻辑 List<CityZip> mergedList = originalList.stream() // 按城市名称分组,同组的邮编用逗号拼接 .collect(Collectors.groupingBy( CityZip::getCity, Collectors.mapping(CityZip::getZipCode, Collectors.joining(",")) )) // 将分组结果转换为去重后的实体集合 .entrySet().stream() .map(entry -> new CityZip(entry.getKey(), entry.getValue())) .collect(Collectors.toList()); // 测试输出 mergedList.forEach(item -> System.out.println(item.getCity() + " : " + item.getZipCode()) ); } }
运行后输出结果符合要求:
madrid : 19,28 barcelona : 08 valencia : 46
普通遍历实现
如果不想用Stream,用Map遍历也可实现相同效果:
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; // 核心逻辑 Map<String, StringBuilder> tempMap = new HashMap<>(); for (CityZip item : originalList) { String city = item.getCity(); String zip = item.getZipCode(); if (tempMap.containsKey(city)) { tempMap.get(city).append(",").append(zip); } else { tempMap.put(city, new StringBuilder(zip)); } } // 转换为最终实体集合 List<CityZip> mergedList = new ArrayList<>(); for (Map.Entry<String, StringBuilder> entry : tempMap.entrySet()) { mergedList.add(new CityZip(entry.getKey(), entry.getValue().toString())); }
保留原始顺序的扩展写法
如果需要保留城市在原始集合中首次出现的顺序,只需要在分组时指定使用LinkedHashMap存储即可:
List<CityZip> orderedMergedList = originalList.stream() .collect(Collectors.groupingBy( CityZip::getCity, LinkedHashMap::new, // 指定有序Map实现 Collectors.mapping(CityZip::getZipCode, Collectors.joining(",")) )) .entrySet().stream() .map(entry -> new CityZip(entry.getKey(), entry.getValue())) .collect(Collectors.toList());
内容的提问来源于stack exchange,提问作者R0b0t0
相关产品推荐
相关产品推荐

