JAVA遍历Map对象的四种方式
方式一:这是最常见的并且在大多数情况下也是最可取的遍历方式。在键值都需要时使用。
1 Map<Integer,String> map = new HashMap<Integer,String>();
2 map.put(1,"a");
3 map.put(2,"b");
4 map.put(3,"ab");
5 map.put(4,"ab");
6 map.put(4,"abc");
7 map.put(4,"abcd");
8
9 for (Map.Entry<Integer, String> entry : map.entrySet()) {
10 System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
11 }
方式二: 在for-each循环中遍历keys或values
如果只需要map中的键或者值,你可以通过keySet或values来实现遍历,而不是用entrySet。
1 Map<Integer,String> map = new HashMap<Integer,String>();
2 //遍历map中的键
3 for (Integer key : map.keySet()) {
4 System.out.println("Key = " + key);
5 }
6 //遍历map中的值
7 for (Integer value : map.values()) {
8 System.out.println("Value = " + value);
9 }
方法三:使用Iterator遍历
使用泛型:
1 Iterator<Map.Entry<Integer,String>> entries = map.entrySet().iterator();
2 while (entries.hasNext()) {
3 Map.Entry<Integer,String> entry = entries.next();
4 System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
5 }
不使用泛型:
Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
Integer key = (Integer)entry.getKey();
Integer value = (Integer)entry.getValue();
System.out.println("Key = " + key + ", Value = " + value);
}
方法四:通过键找值遍历(效率低)
Map<Integer, String> map = new HashMap<Integer, Integer>(); for (Integer key : map.keySet()) { Integer value = map.get(key); System.out.println("Key = " + key + ", Value = " + value);