1. Get the Set collection of keys through Map.keySet, and then traverse through the keys
2. Get all values through Map.values, and then traverse
3. Get the Set collection through Map.entrySet, and then traverse through iterator
4. Traverse the Set collection obtained by Map.entrySet directly through foreach
Case:
public class MapErgodic {
public static void main(String[] args) {
Map<Integer,String> map=new HashMap<Integer,String>();
String[] name= {
"张三","李四","王五","马六","侯七"};
for (int i = 0; i < name.length; i++) {
map.put(i,name[i]);
}
fun1(map);
fun2(map);
fun3(map);
fun3(map);
}
//通过Map.keySet获取key的Set集合,之后在通过key进行遍历
public static void fun1(Map<Integer,String>map){
Set<Integer> s = map.keySet();
for (Integer key : s) {
System.out.println(key+":"+map.get(key));
}
}
//通过Map.values获取所有value,之后再进行遍历
public static void fun2(Map<Integer,String>map){
Collection<String> values = map.values();
for (String value: values) {
System.out.println("value为:" + value);
}
}
//通过Map.entrySet获取Set集合,之后通过iterator进行遍历
public static void fun3(Map<Integer,String>map){
Set<Entry<Integer, String>> set=map.entrySet();
Iterator<Entry<Integer,String>> iterator = set.iterator();
while (iterator.hasNext()){
Entry<Integer, String> entry = iterator.next();
System.out.println( entry.getKey() + ":" + entry.getValue());
}
}
//直接通过foreach对Map.entrySet获取的Set集合进遍历
public static void fun4(Map<Integer,String>map){
for (Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getKey()+" : "+entry.getValue());
}
}
}