1》可以取出Map中所有的键所在的Set集合;再通过Set的迭代器获取到每一个键,之后再用get();方法获得对应的值。
public static void main(String[] args) {
Map<String, String> map=new HashMap<String, String>();
map.put("诶诶", "战神");
map.put("是啥", "发ver");
map.put("草", "傻逼");
//返回map映射中所有的键Set集合并进行迭代
Set set= map.keySet();//获得map中所有键的集合
Iterator iterator=set.iterator();//迭代 获得value
while(iterator.hasNext()){
String key=(String) iterator.next();//所有key值
String value=map.get(key);
System.out.println(key+"-"+value);
}
2》
用entrySet
第一种方式中提到的keySet方法是返回整个Map中所有的键元素,而entrySet方法是返回整个Map中所有的键值元素。
Map<String, String> map=new HashMap<String, String>(); map.put("诶诶", "战神"); map.put("是啥", "发ver"); map.put("草", "傻逼"); Set enSet=map.entrySet(); Iterator it=enSet.iterator(); while(it.hasNext()){ Map.Entry me = (Entry) it.next();//所有键值元素 String key=(String) me.getKey(); String value= (String) me.getValue(); System.out.println(key+"-"+value); }
原文:http://www.cnblogs.com/hgwxr/p/3973321.html