JavaでMapを巡るいくつかの方法

3105 ワード

1.Mapでは、keySet()、value()、entrySet()などの、いくつかの一般的な方法が提供されています。
       keySet()方法:このマップに含まれるキーのセットビューを返します。
    public Set keySet()
       value()方法:このマッピングに含まれる値のcollectionビューを返します。
    public Collection values()
       entrySet()方法:このマッピングに含まれるマッピング関係のcollectionビューを返します。
    public Set> entrySet()
具体的な例:
class HelloWorld
{
	public static void main(String[] args)
	{
		HashMap map = new HashMap();
		map.put("1","one");
		map.put("2","two");
		map.put("3", "tree");
		map.put("4", "four");
		//  keySet  ,        Set  
		System.out.println(map.keySet());
		//  values  ,         Collection
		System.out.println(map.values());
		//entrySet()  ,       -   Set  
		System.out.println(map.entrySet());
	}
}
プログラム運転の結果は、次のように印刷されます。それぞれのキー、すべての値、およびすべてのキーの値の組み合わせが表示されます。
[3, 2, 1, 4]
[tree, two, one, four]
[3=tree, 2=two, 1=one, 4=four]
2.Mapのキーをどのように取り出すかには、3つの一般的な方法があります。
       第一の方法は、まずキーをkeySet()法で取り出してから、反復によってそれぞれ対応する値を取り出すことである。
class HelloWorld
{
	public static void main(String[] args)
	{
		HashMap map = new HashMap();
		map.put("01", "zhangsan");
		map.put("02", "lisi");
		map.put("03", "wangwu");	
		Set set = map.keySet();			//       Set  
		Iterator it = set.iterator();		
		while(it.hasNext())
		{
			String key = it.next();
			String value = map.get(key);		//  get  ,       
			System.out.println(key+" "+value);	//         
		}
	}
}
   
  第二の方法:
class HelloWorld
{
	public static void main(String[] args)
	{
		HashMap map = new HashMap();
		map.put("01", "zhangsan");
		map.put("02", "lisi");
		map.put("03", "wangwu");
		
		Set> entry = map.entrySet();		//         collecton  
		Iterator> it = entry.iterator();
		while(it.hasNext())
		{
			Map.Entry me = it.next();
			System.out.println(me.getKey()+" "+me.getValue());		//  getKey()   
		}									//  getValue()   
	}
}
説明:戻りセットの各要素は、Map.Entryであり、iteraorを介してこのセットにアクセスし、各Map.Entry要素を得て、最後にgetKey()とgetValue()方法でキーと値を得る。
第三の方法(この方法は値を取り出すしかない):
class HelloWorld
{
	public static void main(String[] args)
	{
		HashMap map = new HashMap();
		map.put("01", "zhangsan");
		map.put("02", "lisi");
		map.put("03", "wangwu");
		
		Collection collection = map.values(); //  values         Collection  
		Iterator it = collection.iterator();	
		while(it.hasNext())
		{
			String name = it.next();
			System.out.println(name);				  //       
		}
	}
}