1. 程式人生 > >Java遍歷Map、HashMap

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; } }