博主有时会忘记如何遍历Map对象,这次在这里做一下总结。博主采用的是JDK7,先看一下JDK7中Map接口的定义。
java.util
Interface Map<K,V>
-
- 类型参数:
-
K
- the type of keys maintained by this map -
V
- the type of mapped values
- All Known Subinterfaces:
- Bindings, ConcurrentMap<K,V>, ConcurrentNavigableMap<K,V>, LogicalMessageContext, MessageContext, NavigableMap<K,V>, SOAPMessageContext, SortedMap<K,V>
- All Known Implementing Classes:
- AbstractMap, Attributes, AuthProvider, ConcurrentHashMap, ConcurrentSkipListMap, EnumMap, HashMap, Hashtable, IdentityHashMap, LinkedHashMap, PrinterStateReasons, Properties, Provider, RenderingHints, SimpleBindings, TabularDataSupport, TreeMap, UIDefaults, WeakHashMap
遍历map的方法有很多,最常用的是(特指博主最常用的方式,如有雷同,纯属巧合):
@Test public void test1() { Map<String,String> map = new HashMap<String,String>(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); map.put("key4", "value4"); for(Map.Entry<String, String> entry:map.entrySet()) { System.out.println(entry.getKey()+":"+entry.getValue()); } }上面的方法可以同时获取键和值,当map为null时抛出NullPointerException.
如果只要单独遍历键或者值,也可以采用如下的方法:
@Test public void test2() { Map<String,String> map = new HashMap<String,String>(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); map.put("key4", "value4"); for(String s: map.keySet()) { System.out.println(s); } for(String s:map.values()) { System.out.println(s); } }遍历List比较多的时候,要么习惯用Foreach的方式,要么习惯用Iterator的方式,map的遍历也可以采用Iterator的方式进行遍历。
@Test public void test3() { Map<String,String> map = new HashMap<String,String>(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); map.put("key4", "value4"); Iterator<Map.Entry<String,String>> iter = map.entrySet().iterator(); while(iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); System.out.println(entry.getKey()+":"+entry.getValue()); } }其实上面这种形式和第一种类似,就是把Foreach换成了Iterator,个人推荐第一种,上面这种方式相对第一种遍历方式较麻烦。
如果客官查阅过网上资料,一般说map的遍历方式一般有四种,我已经说了三种了,最后一种是首先遍历key,根据key再使用map.get(key)的方法访问value。这种方式一看效率就低,博主极其不推崇。如下:
@Test public void test4() { Map<String,String> map = new HashMap<String,String>(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); map.put("key4", "value4"); for(String key: map.keySet()) { System.out.println(key+":"+map.get(key)); } }
如何遍历map对象的探讨到此结束,希望对各位有所帮助。