java遍历map对象

一、获取键+值

Map map = new HashMap(); 
for (Map.Entry entry : map.entrySet()) { 
  System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); 
}

二、for循环遍历键/值

Map map = new HashMap(); 
//遍历map中的键 
for (String key : map.keySet()) { 
  System.out.println("Key = " + key); 
} 
//遍历map中的值 
for (String value : map.values()) { 
  System.out.println("Value = " + value); 
}

三、iterator遍历

Map map = new HashMap(); 
Iterator> entries = map.entrySet().iterator(); 
while (entries.hasNext()) { 
  Map.Entry entry = entries.next(); 
  System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); 
}

四、通过键找值遍历

Map map = new HashMap(); 
for (Stringkey : map.keySet()) { 
  String value = map.get(key); 
  System.out.println("Key = " + key + ", Value = " + value);
}

 

你可能感兴趣的:(java,java,Map,HashMap)