java 遍历Map并且获取其中的键值

时间:2022-11-05 19:17:57


import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
 * 遍历map集合中的键值的方法
 * @Description TestMap
 * @author Administrator
 */
public class TestMap {
public static void main(String[] args) {

Map<String,String> map = new HashMap<String, String>();
// 要想有序的输出,用TreeMap
// Map<String,String> map = new TreeMap<String, String>();

map.put("1", "zhangsan");// 向集合中添加对象
map.put("2", "lisi");
map.put("3", "zhaoliu");

System.out.println("方法一");
// 获取Map集合的key的Set集合
Set<String> keySet = map.keySet();
Iterator<String> it = keySet.iterator();
while (it.hasNext()) {
String key = it.next();// 获取Key值对象
String value = map.get(key);// 获取键值对象
System.out.println(key + ":" +value);
}
System.out.println("---------------------");
System.out.println("方法二");
// 获取Map集合的key,value集合Map.Entry<String, String>
Iterator<Map.Entry<String, String>> its = map.entrySet().iterator();
while(its.hasNext()){
Map.Entry<String, String> entryMap = its.next();
String key = entryMap.getKey();
String value = entryMap.getValue();
System.out.println(key + ":" +value);
}
System.out.println("---------------------");
System.out.println("方法三");
// 获取Map集合的value集合
Collection coll = map.values();
for(Object obejct : coll){
String value = obejct.toString();// 获取键值对象
System.out.println(value);
}
}
}