面试必备-Map集合遍历
程序员文章站
2022-12-04 13:52:36
1...
Map集合遍历
package test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class TestMap {
public static void main(String[] args){
Map<String,String> map = new HashMap<>();
map.put("zhangsan", "333");
map.put("lisi", "444");
map.put("wangwu", "555");
map.put("liuliu", "666");
//Map遍历方法一:通过Map.entrySet遍历key和value (推荐使用)
for (Map.Entry<String, String> m : map.entrySet()) {
System.out.println("key:" + m.getKey() + " value:" + m.getValue());
}
//Map遍历方法二:通过迭代器遍历
Iterator<Entry<String, String>> it = map.entrySet().iterator();
while(it.hasNext()){
Entry<String, String> entry = it.next();
System.out.println("key:"+entry.getKey()+" key:"+entry.getValue());
}
//Map遍历方法三:通过Map.keySet()遍历key和value
for(String key:map.keySet()){
String value = map.get(key).toString();//
System.out.println("key:"+key+" vlaue:"+value);
}
//Map遍历方法四:通过Map.values()遍历所有的value,但不能遍历key
for(String m:map.values()){
System.out.println(m);
}
}
}
本文地址:https://blog.csdn.net/weixin_44231137/article/details/109637112
下一篇: Web服务器软件