1. 程式人生 > >Map的四種遍歷方式和兩種刪除方式

Map的四種遍歷方式和兩種刪除方式

首先,建立一個map並存入資料

Map<String,Integer> map=new HashMap<String,Integer>();

map.put("小李", 20);

map.put("校長", 21);

map.put("小王", 25);

一、Map的遍歷

1、遍歷map的key組成的Set集合和value組成的集合(不是Set集合了)

for (String str : map.keySet())

{

System.out.println("key="+str+";value="+map.get(str));

}

for (Integer num : map.values())

{

System.out.println("value="+num);

}

2、遍歷map的entry鍵值對(Set集合)

for (Map.Entry<String, Integer> entry: map.entrySet())

{

System.out.println(entry.getKey()+":"+entry.getValue());

}

3、使用迭代器獲取Map的entry集合從而遍歷

for (Iterator<Map.Entry<String,Integer>> it=map.entrySet().iterator();it.hasNext();)

{

Map.Entry<String, Integer> itt=it.next();

System.out.println(itt.getKey()+":"+itt.getValue());

System.out.println(itt);

}

4、Java1.8中有lambda表示式也可以實現對map的遍歷

map.forEach((k,v)->{System.out.println(k+";"+v);});

二、Map的刪除

Map的刪除主要有兩種方法:

1、最常見的

map.remove("小李");//輸入要刪除的key的值

2、那麼要怎麼根據Map的value刪除鍵值對呢

Iterator<Entry<String, Integer>> it = map.entrySet().iterator();

while (it.hasNext())

{

Entry<String, Integer> tempentry = it.next();

if (tempentry.getValue() == 25)

{

it.remove();

}

}

ps:1、 HashMap原始碼裡沒有做同步操作,多個執行緒操作可能會出現執行緒安全的問題,建議

用Collections.synchronizedMap 來包裝,變成執行緒安全的Map,例如:

Map map = Collections.synchronizedMap(new HashMap<String,String>());

2、任何集合在遍歷時要進行刪除操作時都需要使用迭代器

轉載 http://www.51csdn.cn/article/243.html