HashMap之KeySet、entrySet

package test;

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

/**
 * HashMap是一种无序的存储结构,是基于哈希表Map的实现
 * KeySet :键的集合,Set里面的类型即Key的类型。
 * entrySet:键值对集合,Set里面的类型即 Map.Entry.
 */
public class TestEntrySet {
	public static void main(String[] args) {
		Map map = new HashMap();
		map.put("1", "Java");
		map.put("2", "C++");
		map.put("3", "C");
		//1.普通使用
		System.out.println("通过Map.keySet遍历Key和Value:");
		for (String key : map.keySet()) {
			System.out.println("Key = " + key + ",Vaule= " + map.get(key));
		}
		//2.map.entrySet().iterator()
		System.out.println("通过Map.entrySet使用iterator遍历key和vale:");
		Iterator> it = map.entrySet().iterator();
		while(it.hasNext()){
			Map.Entry entry = it.next();
			System.out.println("Key = " + entry.getKey() +",Value = " + entry.getValue());
		}
		//3.(推荐)尤其是容量大时
		System.out.println("通过Map.entrySet遍历key和vale:");
		for(Map.Entry entry : map.entrySet()){
			System.out.println("Key = " + entry.getKey() +",Value = " + entry.getValue());
		}
		//4.仅能遍历value
		System.out.println("通过Map.values()遍历所有Value,但不能遍历Key");
		for (String v : map.values()) {
			System.out.println("Vaule = " + v);
		}
		System.out.println("entrySetTestCode测试方法==================");
		//entrySetTestCode测试方法
		entrySetTestCode();
		System.out.println("keySetTestCode测试方法==================");
		//keySetTestCode测试方法
		keySetTestCode();
	}
	
	public static void entrySetTestCode(){
		Map map = new HashMap();
		map.put("1", "Java");
		map.put("2", "C++");
		map.put("3", "C");
		Iterator it = (Iterator) map.entrySet().iterator();
		String key;
		String value;
		while(it.hasNext()){
			Map.Entry entry = (Entry) it.next();
			key = entry.getKey();
			value = entry.getValue();
			System.out.println("key = " + key +", value=" + value);
		}
	}
	
	public static void keySetTestCode(){
		Map map = new HashMap();
		map.put("1", "Java");
		map.put("2", "C++");
		map.put("3", "C");
		for (String k : map.keySet()) {
			System.out.println("Key = " + k + ",Value = " + map.get(k));
		}
	}
}

打印信息:

通过Map.keySet遍历Key和Value:
Key = 3,Vaule= C
Key = 2,Vaule= C++
Key = 1,Vaule= Java
通过Map.entrySet使用iterator遍历key和vale:
Key = 3,Value = C
Key = 2,Value = C++
Key = 1,Value = Java
通过Map.entrySet遍历key和vale:
Key = 3,Value = C
Key = 2,Value = C++
Key = 1,Value = Java
通过Map.values()遍历所有Value,但不能遍历Key
Vaule = C
Vaule = C++
Vaule = Java
entrySetTestCode测试方法==================
key = 3, value=C
key = 2, value=C++
key = 1, value=Java
keySetTestCode测试方法==================
Key = 3,Value = C
Key = 2,Value = C++
Key = 1,Value = Java
 

你可能感兴趣的:(java)