java8中map有一个merge方法使用示例:
/** * 打印出包含号码集的label的集合 * * @param args */ public static void main(String[] args) { Set<String> mdnSet1 = new HashSet<>(); Set<String> mdnSet2 = new HashSet<>(); Set<String> mdnSet3 = new HashSet<>(); mdnSet1.add("133"); mdnSet1.add("153"); mdnSet2.add("133"); mdnSet2.add("189"); mdnSet3.add("133"); mdnSet3.add("189"); // 133_LABELA:LABELB:LABELC;153_LABELA;189_LABELC:LABELB Map<String, Set<String>> labels = new HashMap<>(); labels.put("LABELA", mdnSet1); labels.put("LABELB", mdnSet2); labels.put("LABELC", mdnSet3); // 将内容存到map中,号码为key,label为value Map<String, String> mdnLabels = new ConcurrentHashMap<>(); for (Entry<String, Set<String>> entry : labels.entrySet()) { Set<String> mdnList = entry.getValue();// mdns String label = entry.getKey();// label for (String mdn : mdnList) { if (mdnLabels.get(mdn) == null) {// 首次放入手机号 mdnLabels.put(mdn, mdn + "_" + label); } else {//其他 mdnLabels.merge(mdn, label, (value, newValue) -> value.concat(":" + newValue));//将label中的 } } } System.out.println(mdnLabels); }