遍历map的方法

方法一:通过map.entrySet(效率较高)

package com.java.call.db;

import java.util.HashMap;
import java.util.Map;

public class SaaMap {
	public static void main(String args[]){
		Map map=new HashMap();
		map.put("a", "1");
		map.put("b","2");
		map.put("c", "3");
		map.put("d", "4");
		map.put("e", "5");
		for(java.util.Iterator iter=map.entrySet().iterator();iter.hasNext();){
			Map.Entry entry=(Map.Entry)iter.next();
			Object key=entry.getKey();
			Object val=entry.getValue();
			System.out.println("key="+key);
			System.out.println("Value="+val);
		}
	}

}












方法二:通过map.keySet(相当于二重循环,效率较低)

package com.java.call.db;

import java.util.HashMap;
import java.util.Map;

public class SaaMap {
	public static void main(String args[]){
		Map map=new HashMap();
		map.put("a", "1");
		map.put("b","2");
		map.put("c", "3");
		map.put("d", "4");
		map.put("e", "5");
	for (Iterator iter = map.keySet().iterator(); iter.hasNext();) { 
      Object key = iter.next(); 
      Object val = map.get(key); 
      System.out.println("key:"+key); 
      System.out.println("value:"+val); 
  }
	}

}

你可能感兴趣的:(java,C++,c,C#)