#遍历Map的几种方式
方法一
1 2 3
| for (String key : map.keySet()){ System.out.println("key= "+ key + " and value= " + map.get(key)); }
|
方法二
1 2 3 4 5
| Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); }
|
方法三 (推荐)
1 2 3
| for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); }
|
方法四
1 2 3
| for (String v : map.values()) { System.out.println("value= " + v); }
|
顺便把遍历proerties也说下,有点类似
初始化proerties
1 2
| Properties prop = new Properties();
|
方法一:
1 2 3 4 5 6
| Enumeration<String> eee = (Enumeration<String>) prop.propertyNames(); while (eee.hasMoreElements()) { String key = (String) eee.nextElement(); String value = prop.getProperty(key); System.out.println("key= "+ key + " and value= " +value); }
|
方法二:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| Enumeration<Object> enu = prop.elements(); while (enu.hasMoreElements()) { Object value = enu.nextElement(); System.out.println(value); } ````
## 方法三: ```java Iterator<Entry<Object, Object>> it = prop.entrySet().iterator(); while (it.hasNext()) { Entry<Object, Object> entry = it.next(); Object key = entry.getKey(); Object value = entry.getValue(); System.out.println("key :" + key+",value:"+value); }
|
您的打赏,是我创作的动力!不给钱?那我只能靠想象力充饥了。
微信支付
支付宝