Map 集合資料遍歷
阿新 • • 發佈:2019-02-17
方法一 獲取key 和value
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
方法二 遍歷keys或values。
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); //遍歷map中的鍵 for (Integer key : map.keySet()) { System.out.println("Key = " + key); } //遍歷map中的值 for (Integer value : map.values()) { System.out.println("Value = " + value); }
方法三使用Iterator遍歷
使用泛型:
- Map<Integer, Integer> map = new HashMap<Integer, Integer>();
- Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
- while (entries.hasNext()) {
- Map.Entry<Integer, Integer> entry = entries.next();
-
System.out.println("Key = "
- }
不使用泛型:
- Map map = new HashMap();
- Iterator entries = map.entrySet().iterator();
- while (entries.hasNext()) {
- Map.Entry entry = (Map.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<Integer, Integer>();
- for (Integer key : map.keySet()) {
- Integer value = map.get(key);
- System.out.println("Key = " + key + ", Value = " + value);
- }