Map遍历方式总结

Map遍历主要有三种方式:

(1) foreach 循环遍历entrySet()

(2)foreach循环遍历KeySet()

(3)迭代器iterator遍历entrySet()

代码如下

public static void main(String[] args) {
Map map = new HashMap();
map.put("y", "1");
map.put("t", "2");
//--one way
Iterator it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry entry = (Entry) it.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+"1:"+value);
}
//--two way
for(Map.Entry entry:map.entrySet()){
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+"2:"+value);
}
//three way
for(String str:map.keySet()){
String key = str;
String value = map.get(key);
System.out.println(key+"3:"+value);

}
}


你可能感兴趣的:(Map遍历方式总结)