java8中map的meger方法的使用


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);

	}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM