Java中,通常有两种遍历HashMap的方法,如下:
- import java.util.*;
- public class MapTest {
- static HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
- public static void main(String [] args) {
- hashMap.put("one", 1);
- hashMap.put("two", 2);
- hashMap.put("three", 3);
- hashMap.put("four", 4);
- hashMap.put("five", 5);
- Iterator iter = hashMap.entrySet().iterator();
- // the first method to travel the map
- while (iter.hasNext()) {
- Map.Entry<String, Integer> entry = (Map.Entry<String, Integer>) iter.next();
- String key = entry.getKey();
- Integer value = entry.getValue();
- System.out.println(key + " " + value);
- }
- iter = hashMap.keySet().iterator();
- // the second method to travel the map
- while (iter.hasNext()) {
- String key = (String) iter.next();
- Integer value = hashMap.get(key);
- System.out.println(key + " " + value);
- }
- } // close main()
- }
第一种效率要高于第二种,应尽量使用第一种进行遍历。
本文介绍了两种常用的遍历Java中HashMap的方法,并对比了它们的效率。第一种方法通过迭代器遍历entrySet,第二种方法通过迭代器遍历keySet再获取对应的值。文章建议优先采用第一种方法以提高遍历效率。
452

被折叠的 条评论
为什么被折叠?



