Java中遍历HashMap的技巧
发布时间:2021-11-22 11:44:02 所属栏目:教程 来源:互联网
导读:Java中,通常有两种遍历HashMap的方法,如下: import java.util.*; publicclass MapTest { static HashMapString, Integer hashMap = new HashMapString, Integer(); publicstaticvoid main(String [] args) { hashMap.put(one, 1); hashMap.put(two, 2); h
Java中,通常有两种遍历HashMap的方法,如下: import java.util.*; publicclass MapTest { static HashMap<String, Integer> hashMap = new HashMap<String, Integer>(); publicstaticvoid 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() } 第一种效率要高于第二种,应尽量使用第一种进行遍历。 ![]() (编辑:PHP编程网 - 黄冈站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |