package test;
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;
/*
* map遍历的几种方法
*/
public class MapInterator {
public static void main(String args[]){
Map<String, String> map = new HashMap<String,String>();
map.put("1","one");
map.put("2","two");
map.put("3","three");
map.put("4","four");
System.out.println("-----------1------------");
function1(map);
System.out.println("------------2-----------");
function2(map);
System.out.println("-----------3------------");
function3(map);
System.out.println("-------------4----------");
function4(map);
}
/*
* 第一种:通过map.keySet(),遍历key,通过key拿value
*/
public static <V, K> void function1(Map<K,V> m){
for(K key: m.keySet()){
V v= m.get(key);
System.out.println(v);
}
}
/*
* 第二种:通过map.entrySet().iterator()拿到iterator;通过iterator.next()拿到Entry<K,V>,拿到value
*/
public static <K, V> void function2(Map<K,V> m){
Iterator<Entry<K, V>> it= m.entrySet().iterator();
while(it.hasNext()){
Entry<K,V> entry=it.next();
V v=entry.getValue();
System.out.println(v);
}
}
/*
* 第三种:通过map.entrySet(),遍历Entry<K,V>
*/
public static <K, V> void function3(Map<K,V> m){
Set<Entry<K,V>> entry = m.entrySet();
for(Entry<K,V>e:entry){
V v = e.getValue();
System.out.println(v);
}
}
/*
* 第四种:通过map.values(),遍历value
*/
public static <K, V> void function4(Map<K,V> m){
Collection<V> cv =m.values();
for(V v:cv){
System.out.println(v);
}
}
}