关于HashMap的遍历总共有4种方法:
1. 在for-each循环中使用entries来遍历
2. 在for-each循环中遍历keys或values
3. 使用Iterator遍历
4. 通过键找值遍历
下面,我们将依次讲述这几种方法:
方法一:在for-each循环中使用entries来遍历
HashMap<Integer, Integer> map = new HashMap<>();
for(Map.Entry<Integer,Integer> entry:map.entrySet()){
System.out.println("key = "+entry.getKey()+",value="+entry.getValue());
}
方法二:在for-each循环中遍历keys或values
HashMap<Integer,Integer> map = new HashMap<>();
for(Integer key : map.keySet()){
System.out.println("key = "+key);
}
for(Integer value : map.values()){
System.out.println("value = "+ value);
}
方法三:使用Iterator遍历
使用泛型:
Map<Integer,Integer> map = new HashMap<>();
Iterator<Map.Entry<Integer,Integer>> entries = map.entrySet().iterator();
while(entries.hasNext()){
Map.Entry<Integer,Integer> entry = entries.next();
System.out.println("key = "+ entry.getKey()+"value = "+entry.getValue());
}
不使用泛型:
Map<Integer,Integer> map = new HashMap<>();
Iterator<Map.Entry<Integer,Integer>> entries = map.entrySet().iterator();
while(entries.hasNext()){
Map.Entry<Integer,Integer> entry = entries.next();
Integer key = (Integer)entry.getKey();
Integer value = (Integer)entry.getValue();
System.out.println("key = "+key+",value="+value);
}
方法四:通过键值找遍历
Map<Integer,Integer> map = new HashMap<>();
for(Integer key : map.keySet()){
Integer value = map.get(key);
System.out.println("key = "+key+"value="+value);
}