遍历Map的几种方式

遍历Map的几种方式

方法一

Person p1=new Person( 1,"what");

Person p2=new Person( 1,"张明");

Map<Integer,Person> map=new HashMap<Integer, Person>();

map.put( 1, p1);

map.put( 2, p2);

         

//遍历map集合

for(Map.Entry<Integer, Person> a:map.entrySet()){

  System.out.println("键是"+a.getKey());

  System.out.println("值是"+a.getValue());

}

方法二

Map map = newHashMap();

map.put( 1, "Jacky");

map.put( 2, "Lucy");

map.put( 3, "Tom");

Iterator it = map.entrySet().iterator();

while(it.hasNext()){

Map.Entry entry = (Map.Entry) it.next();

System.out.println(entry.getKey() + " : " + entry.getValue());

}

方法三

Iterator it=map.keySet().iterator();

while(it.hasNext()){

 //取出key

 String key=it.next().toString();

 System.out.println(key);

 //通过key拿到value

 String str1=(String) map.get(key);

 System.out.println(str1);

}

你可能感兴趣的:(java,in,basic)