Java遍历Map、HashMap

下面介绍三种方法遍历:

package easy;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class hashmap {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("username","zhaokuo");
			map.put("password", "123456");
			map.put("email", "[email protected]");
			map.put("sex", "男");
			
			//第一种 用for循环的方式,所用方法头部public Set<Map.Entry<K,V>> entrySet()
			for (Map.Entry<String, Object> m :map.entrySet())  {
				System.out.println(m.getKey()+"\t"+m.getValue());
			}
			System.out.println(".................................");
			//第二种利用迭代 (Iterator),和EnteySet
			Set set=map.entrySet();
			Iterator iterator=set.iterator();
			while(iterator.hasNext()){
					Map.Entry enter=(Map.Entry) iterator.next();
					System.out.println(enter.getKey()+"\t"+enter.getValue());
			}
			System.out.println("================================");
			
			//第三种利用KeySet 迭代
			Iterator it = map.keySet().iterator();
			while(it.hasNext()){
				 String key;   
			     String value;   
			     key=it.next().toString();   
			     value=(String) map.get(key);   
			     System.out.println(key+"--"+value);   
			}
			System.out.println("---------------------------");
			
			
			System.out.println(getKeyByValue(map, "zhaokuo"));
		}
		//根据Value取Key
		public static String getKeyByValue(Map map, Object value) {
			String keys="";
			Iterator it = map.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry entry = (Entry) it.next();
				Object obj = entry.getValue();
				if (obj != null && obj.equals(value)) {
					keys=(String) entry.getKey();
				}
			}
			return keys;
			}
	
}

猜你喜欢

转载自blog.csdn.net/qq_30122883/article/details/82958196