Map扩展知识
map集合被使用是具备映射关系
“bigclass”: “001”, ”zhangsan”
“002”, ”lisi”
“smallclass” : ”001”, “wangwu”
:”002”, “zhaoliu”
一个学校有多个班级,每个班级都有自己的名字
代码示例:
package CollectionTest; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class HashMapDemo4 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub //解决映射中的一对多问题。 Map<String,String> one = new HashMap<String,String>(); one.put("001", "zhangsan"); one.put("002", "lisi"); Map<String,String> two = new HashMap<String,String>(); two.put("001", "wangwu"); two.put("002", "zhaoliu"); HashMap<String,HashMap<String,String>> school = new HashMap<String,HashMap<String,String>>(); school.put("bigclass", (HashMap<String, String>) one); school.put("smallclass", (HashMap<String, String>) two); //遍历school,获取所有班级(通过KeySet方法获得是所有键的String类型) Iterator<String> it= school.keySet().iterator(); while(it.hasNext()){ String roomName = it.next(); System.out.println(roomName); //通过school的get方法,里面传入的是键,获得one,two Map<String,String> room = school.get(roomName); getInfo(room); } } public static void getInfo(Map<String,String> roomMap){ Iterator<String> it = roomMap.keySet().iterator(); while(it.hasNext()){ String id = it.next(); String name = roomMap.get(id); System.out.println(id+":"+name); } } }
第二种方法:
package CollectionTest; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; class Student3{ private String id; 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; } private String name; Student3(String id,String name){ this.id=id; this.name=name; } public String toString(){ return id+","+name; } } public class HashMapDemo4 { /** * @param args */ public static void demo(){ HashMap<String,List<Student3>> school = new HashMap<String,List<Student3>>(); List<Student3> big = new ArrayList<Student3>(); List<Student3> small= new ArrayList<Student3>(); school.put("big", big); school.put("small", small); big.add(new Student3("001","zhangsan")); big.add(new Student3("002","lisi")); small.add(new Student3("001","wangwu")); small.add(new Student3("002","zhaoliu")); Iterator<String> it = school.keySet().iterator(); while(it.hasNext()){ String roomName = it.next(); List<Student3> stu = school.get(roomName); System.out.println(roomName); getInfors(stu); } } public static void getInfors(List<Student3> list){ Iterator<Student3> it2 = list.iterator(); while(it2.hasNext()){ Student3 s = it2.next(); System.out.println(s); } } public static void main(String[] args) { // TODO Auto-generated method stub demo(); } }