1.通过Map.keySet遍历key和value
map.keySet()返回的是所有key的值
map.get(in)得到每个key对应value的值
2.通过Map.keySet使用iterator遍历key和value
方法同上
3.通过Map.entrySet遍历key和value
map.entrySet() 返回此映射中包含的映射关系的 Set视图。
4.通过Map.entrySet使用iterator遍历key和value
方法同上
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class MapTest {
public static void main(String[] args) {
MapBianli1();
MapBianli2();
MapBianli3();
MapBianli4();
}
/**
* 获取keySet,得到一个个的key
* map.get()获取key所对应的value
*
*/
public static void MapBianli1(){
Map<String,String> map = new HashMap<String, String>();
map.put("name","马云");
map.put("age","28");
map.put("gender","男");
map.put("major","电子商务");
System.out.println("方法一");
for(String key:map.keySet()){
System.out.println(key+": "+map.get(key) );
}
}
/**
* 获取entrySet,entrySet装的是一个个键值对
* entrySet.getKey获取key,entrySet.getValue获取value
*/
public static void MapBianli2(){
Map<String,String> map = new HashMap<String, String>();
map.put("name","马云");
map.put("age","28");
map.put("gender","男");
map.put("major","电子商务");
System.out.println("方法二");
Set<Map.Entry<String, String>> entrySet = map.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
System.out.println(entry.getKey()+": "+entry.getValue());
}
}
/**
*利用迭代器遍历重复keySet的遍历方法
*/
public static void MapBianli3(){
Map<String,String> map = new HashMap<String, String>();
map.put("name","马云");
map.put("age","28");
map.put("gender","男");
map.put("major","电子商务");
System.out.println("方法三");
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()){
String key = iterator.next();
System.out.println(key+": "+map.get(key));
}
}
/**
* 利用迭代器重复entrySet的遍历方法
*/
public static void MapBianli4(){
Map<String,String> map = new HashMap<String, String>();
map.put("name","马云");
map.put("age","28");
map.put("gender","男");
map.put("major","电子商务");
System.out.println("方法四");
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<String, String> entry = iterator.next();
System.out.println(entry.getKey()+": "+entry.getValue());
}
}
}
来源:CSDN
作者:南方_少年
链接:https://blog.csdn.net/apache_ant/article/details/104114281