循环输出HashMap

@Test
public void mapTest(){
Map map = new HashMap();
map.put("1", "2");
map.put("w", "r");
map.put("e", "4");
//方法一 HashMap entrySet()
Iterator it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry m = (Map.Entry) it.next();
System.out.println(m.getKey() + ":" + m.getValue());
}
System.out.println("*****************");
//方法二  for-each循环
for(Entry ent:map.entrySet()){
System.out.println(ent.getKey().toString() + ":" + ent.getValue().toString());
}
System.out.println("*****************");
//方法三 hashMap keySet()
for(Iterator mi = map.keySet().iterator();mi.hasNext();){
Object obj = mi.next();
System.out.println(obj + ":" + map.get(obj));
}
System.out.println("*****************");
//方法四 treemap keySet()遍历  
for (Object o : map.keySet()) {  
   System.out.println("key=" + o + " value=" + map.get(o));  
}  
System.out.println("*****************");

List arrList = new ArrayList();
arrList.add("a");
arrList.add("b");
arrList.add("c");
arrList.add("d");
Map mapArr = new HashMap();
mapArr.put("1", arrList);
mapArr.put("2", arrList);
mapArr.put("3", arrList);
/*for(Object o:mapArr.keySet()){
System.out.print("key="+o + "-->") ;
ArrayList arr = (ArrayList) mapArr.get(o);
for(String st:arr){
System.out.println(st);
}
}*/

Iterator arrIt = mapArr.entrySet().iterator();
while(arrIt.hasNext()){
Map.Entry m = (Map.Entry) arrIt.next();
ArrayList arr = (ArrayList) m.getValue();
System.out.print("key="+m.getKey() + "-->") ;
for(String st:arr){
System.out.println(st);
}
}

}

输出结果:

w:r
1:2
e:4
*****************
w:r
1:2
e:4
*****************
w:r
1:2
e:4
*****************
key=w value=r
key=1 value=2
key=e value=4
*****************
key=3-->a
b
c
d
key=2-->a
b
c
d
key=1-->a
b
c
d

你可能感兴趣的:(java)