java中遍历map有三种方式,代码如下:
package com.yuansheng.console.sysuser;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class Test {
public static void main(String[] args) {
Map<String, Object> map=new HashMap<String, Object>();
map.put("a", 1);
map.put("b", "中国");
map.put("c", true);
// testValues(map);
// testKeySet(map);
testEntrySet(map);
}
/**
* 1,获取所有values,遍历
* @param map
*/
public static void testValues(Map<String, Object> map){
Collection<Object> values=map.values();
for(Object v:values){
System.out.println(v.toString());
}
}
/**
* 2,获取所有的key,进而可获取到对应的value
* @param map
*/
public static void testKeySet(Map<String, Object> map){
Set<String> keySet=map.keySet();
for(String key:keySet){
System.out.println(key+","+map.get(key));
}
}
/**
* 3,利用entrySet进行遍历,一般认为效率最高
* @param map
*/
public static void testEntrySet(Map<String, Object> map){
Set<Entry<String, Object>> entrySet=map.entrySet();
Iterator<Entry<String, Object>> iterator=entrySet.iterator();
while (iterator.hasNext()) {
Entry<String, Object> entry=iterator.next();
System.out.println(entry.getKey()+","+entry.getValue());
}
}
}