Map的遍历
- entrySet遍历
java
Map<Integer, Integer> map = new HashMap<>();
// 向map中添加一些元素
map.put(1, 100);
map.put(2, 200);
map.put(3, 300);
for(Map.Entry<Integer, Integer> entry: map.entrySet()){
Integer key = entry.getKey();
Integer value = entry.getValue();
System.out.println("key:" + key + "value:" + value);
}
- keySet遍历
java
for(Integer key: map.keySet()){
Integer value = map.get(key);
System.out.println("key:" + key + "value:" + value);
}
- valuses遍历
java
for(Integer value: map.valuses()){
Integer value = map.get(key);
System.out.println("value:" + value);
}
- Iterator遍历
java
Iterator<Map.Entry<Integer, Integer>> iterator= map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<Integer, Integer> entry = itreator.next();
Integer key = entry.getKey();
Integer value = entry.getValue();
System.out.println("key:" + key + "value:" + value);
}