今天一朋友問我有關Map集合的遍歷問題,說真的當時真是懵了似懂非懂的,下面我通過查閱資料,具體內容整理如下:
1
2
3
4
5
6
|
public static void main(String[] args){ Map<String,String> map= new HashMap<String,String>(); map.put( "1" , "張三" ); map.put( "2" , "李四" ); map.put( "3" , "王五" ); } |
第一種方法:通過Map.keySet遍歷key和value
1
2
3
4
|
for (String key:map.keySet()){ System.out.print( "key=" +key); System.out.println( "value=" +map.get(key)); } |
第二種方法:通過Map.entrySet和迭代器遍歷Map
1
2
3
4
5
6
|
Iterator<Map.Entry<String,String>> car =map.entrySet().interator(); while (car.hasNext()){ Map.Entry<String,String> entry=car.next(); System.out.println( "key=" +entry.getKey()+ "and value=" +entry.getValue()); } |
第三種方法:Map.entrySet()加for in 循環(推薦):
1
2
3
4
|
for (Map.Entry<String,String> entry:map.entrySet()){ System.out.println( "key=" +entry.getKey()+ "and value=" +entry.getValue()); } |
注:Map.entrySet()返回的是一個Set<Map<k,v>>,Map.Entry是一個接口,表示一個鍵值對(映射項),而Set<Map<k,v>>則表示映射項的Set。
第四種方法:通過Map.values():
1
2
3
4
|
for (String val:map.Values()){ System.out.println( "value=" +v); } |
以上四種方法介紹了Map集合的遍歷代碼,希望能夠幫助到大家。