相信很多人都對java的集合知識都有所了解,這是一些基礎知識,而且也是JAVA開發的必備知識,對於開發經驗稍微豐富一些的工程師,對於三個集合接口的應用肯定也是爐火純青了。好了,不廢話,直奔主題:map集合處理一對多。
map:其結構是{key1=value1,key2=value2,key3=value1,key4=value3……}
key:唯一,不可可重復。
value:可重復,任何元素。
而map處理一對多,就是利用了map的特性。
直接上代碼:
import java.util.HashMap; import java.util.Map; public class Test { public static Map<String,String> data() { Map<String,String> map = new HashMap<String,String>(); map.put("a#1", "m"); map.put("b#2", "n"); map.put("c", "o"); map.put("d#1", "x"); map.put("e#2", "y"); return map; } public static void main(String[] args) { Map<String,Map<String,String>> finalMap = new HashMap<String,Map<String,String>>(); Map<String,String> list = new HashMap<String,String>(); Map<String,String> map = data(); for(String key:map.keySet()){ if(key.contains("#")){ String newMapKey = key.substring(key.indexOf("#"),key.length()); if(finalMap.containsKey(newMapKey)){ Map<String,String> tool = finalMap.get(newMapKey); tool.put(key.replaceAll(newMapKey, ""), map.get(key)); }else{ Map<String,String> newMap = new HashMap<String,String>(); newMap.put(key.replaceAll(newMapKey, ""), map.get(key)); finalMap.put(newMapKey, newMap); } }else{ list.put(key, map.get(key)); } } System.out.println(finalMap.size()); System.out.println(list.size()); } }
感興趣的小伙伴,可以把這個測試類跑起來,看看最終的結果,建議使用debug模式,看看每一步的參數和最終的結果,你會發現,里面存在一個很巧妙的想法,就在main方法的第二個判斷里面。