java Map集合嵌套,value为Map和value为List.
import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; public class MapDemo { public static void main(String[] args) { System.out.println("Map集合的值为Map"); oneToMap(); System.out.println("Map集合的值为List,特别常用!必须会!"); oneToList(); } /* * 这种是把班级和学生作为映射 * 而且又把学号和姓名做了映射 */public static void oneToMap() { Map<STRING,MAP<STRING,STRING>> jiSuanJi = new HashMap<STRING,MAP<STRING,STRING>>(); Map<STRING,STRING> ruanJian = new HashMap<STRING,STRING>(); Map<STRING,STRING> wangZhan = new HashMap<STRING,STRING>(); /* * 千万不要每次都new一个进去,这样就不是原来的集合了 * 结果yingyong这个key对应的value集合是null * 遍历Map的时候还会出现空指针错误 *///jiSuanJi.put("yingyong", (Map<STRING, String>) new HashMap().put("01", "haha")); //jiSuanJi.put("yingyong", (Map<STRING, String>) new HashMap().put("02", "xixi")); /* * 要使用下面这种方式,先把集合定义好, * 把映射关系设置好,再去给集合添加元素 */jiSuanJi.put("ruanJian", ruanJian); jiSuanJi.put("wangZhan", wangZhan); ruanJian.put("01", "zhangsan"); ruanJian.put("02", "lisi"); wangZhan.put("01", "zhaoliu"); wangZhan.put("02", "zhouqi"); Set<STRING> keySet = jiSuanJi.keySet(); for(Iterator<STRING> it = keySet.iterator();it.hasNext();) { String key = it.next(); System.out.println(key); Map<STRING,STRING> map = jiSuanJi.get(key); Set<MAP.ENTRY<STRING, String>> entrySet = map.entrySet(); for(Iterator<MAP.ENTRY<STRING, String>> it2 = entrySet.iterator();it2.hasNext();) { Map.Entry<STRING, String> me = it2.next(); System.out.println(me.getKey() + ".." + me.getValue()); } } } /* * 这种把班级和学生做了映射 * 学生类中封装了学号和姓名 */public static void oneToList() { Map<STRING,LIST<PERSONDEMO>> jiSuanJi = new HashMap<STRING,LIST<PERSONDEMO>>(); List<PERSONDEMO> ruanJian = new ArrayList<PERSONDEMO>(); List<PERSONDEMO> wangZhan = new ArrayList<PERSONDEMO>(); jiSuanJi.put("ruanJian", ruanJian); jiSuanJi.put("wangZhan", wangZhan); ruanJian.add(new PersonDemo("01","zhangsan")); ruanJian.add(new PersonDemo("02","lisi")); wangZhan.add(new PersonDemo("01","wangwu")); wangZhan.add(new PersonDemo("02","zhaoliu")); Set<STRING> keySet = jiSuanJi.keySet(); for(Iterator<STRING> it = keySet.iterator();it.hasNext();){ String key = it.next(); System.out.println(key); List<PERSONDEMO> list = jiSuanJi.get(key); for(Iterator<PERSONDEMO> it2 = list.iterator();it2.hasNext();) { PersonDemo pd = it2.next(); System.out.println(pd); } } } } class PersonDemo { private String id; private String name; public PersonDemo(String id, String name) { super(); this.id = id; this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Overridepublic String toString() { return this.id + "..." + this.name; } }