java map集合 --遍歷

1.Map 遍歷:

Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "a");
map.put(2, "b");
map.put(3, "ab");
map.put(4, "ab");
map.put(4, "ab");// 和上面相同 , 會本身篩選
System.out.println(map.size());
// 第一種:
System.out.println("第一種:經過Map.keySet遍歷key和value:");
for (Integer in : map.keySet()) {
    //map.keySet()返回的是全部key的值
    String str = map.get(in);//獲得每一個key多對用value的值
    System.out.println(in + "     " + str);
}
// 第二種:
System.out.println("第二種:經過Map.entrySet使用iterator遍歷key和value:");
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry<Integer, String> entry = it.next();
    System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
// 第三種:推薦,尤爲是容量大時
System.out.println("第三種:經過Map.entrySet遍歷key和value");
for (Map.Entry<Integer, String> entry : map.entrySet()) {
    System.out.println("key= " + entry.getKey() + " and value= "+ entry.getValue());
}
// 第四種:
System.out.println("第四種:經過Map.values()遍歷全部的value,但不能遍歷key");
for (String v : map.values()) {
    System.out.println("value= " + v);
}

 

2.map的長度:

int size=Map.size();spa

相關文章
相關標籤/搜索