package collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* 遍历HanhMap
* @author Wanglei
* @Date 2016年8月18日
*/
public class ErgodicHashMap {
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("1", 100);
map.put("2", 200);
map.put("3", 300);
//ergodic1(map);
// ergodic2(map);
//ergodic3(map);
ergodic4(map);
}
/**
* 遍历方法1
* 通过Map.keySet遍历key和value
*/
public static void ergodic1(Map<String,Integer> map){
if(map != null){
for(String key:map.keySet()){
System.out.println("key="+key+", value="+map.get(key));
}
}
}
/**
* 遍历方法2,不能遍历key
* 通过Map.values()遍历所有的value,但不能遍历key
*/
public static void ergodic2(Map<String,Integer> map){
for(Integer i : map.values()){
System.out.println(i);
}
}
/**
* 遍历方法3
* 通过Map.entrySet使用iterator遍历key和value
*/
public static void ergodic3(Map<String,Integer> map){
Iterator<Map.Entry<String,Integer>> it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String,Integer> entry = it.next();
System.out.println("key="+entry.getKey()+", value="+entry.getValue());
}
}
/**
* 遍历方法4
* 推荐,尤其容量大时
* 通过Map.entrySet遍历key和value
*/
public static void ergodic4(Map<String,Integer> map){
for(Map.Entry<String,Integer> entry : map.entrySet()){
System.out.println("key="+entry.getKey()+", value="+entry.getValue());
}
}
}
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* 遍历HanhMap
* @author Wanglei
* @Date 2016年8月18日
*/
public class ErgodicHashMap {
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("1", 100);
map.put("2", 200);
map.put("3", 300);
//ergodic1(map);
// ergodic2(map);
//ergodic3(map);
ergodic4(map);
}
/**
* 遍历方法1
* 通过Map.keySet遍历key和value
*/
public static void ergodic1(Map<String,Integer> map){
if(map != null){
for(String key:map.keySet()){
System.out.println("key="+key+", value="+map.get(key));
}
}
}
/**
* 遍历方法2,不能遍历key
* 通过Map.values()遍历所有的value,但不能遍历key
*/
public static void ergodic2(Map<String,Integer> map){
for(Integer i : map.values()){
System.out.println(i);
}
}
/**
* 遍历方法3
* 通过Map.entrySet使用iterator遍历key和value
*/
public static void ergodic3(Map<String,Integer> map){
Iterator<Map.Entry<String,Integer>> it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String,Integer> entry = it.next();
System.out.println("key="+entry.getKey()+", value="+entry.getValue());
}
}
/**
* 遍历方法4
* 推荐,尤其容量大时
* 通过Map.entrySet遍历key和value
*/
public static void ergodic4(Map<String,Integer> map){
for(Map.Entry<String,Integer> entry : map.entrySet()){
System.out.println("key="+entry.getKey()+", value="+entry.getValue());
}
}
}