1. 程式人生 > >java學習——Map的四種遍歷方法

java學習——Map的四種遍歷方法

Map是java中的介面,Map.Entry是Map的一個內部介面。

         Map提供了一些常用方法,如keySet()、entrySet()等方法,keySet()方法返回值是Map中key值的集合;entrySet()的返回值也是返回一個Set集合,此集合的型別為Map.Entry。

         Map.Entry是Map宣告的一個內部介面,此介面為泛型,定義為Entry<K,V>。它表示Map中的一個實體(一個key-value對)。介面中有getKey(),getValue方法。

下面是遍歷Map的四種方法:

package script;

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

public class MapDemo {
    public static void main(String[] args){
        Map<String,String> map=new HashMap<String,String>();
        map.put("1","value1");
        map.put("2","value2");
        map.put("3","value3");

        System.out.println("通過Map.KeySet遍歷key和value:");
        for(String key:map.keySet()){
            System.out.println("key="+key+" and vlaue= "+map.get(key));
        }

        //第二種
        System.out.println("通過Map.entrySet使用iterator遍歷key和value:");
        Iterator<Map.Entry<String,String>> it=map.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<String,String> entry=it.next();
            System.out.println("key= "+entry.getKey()+", value= "+entry.getValue());
            //System.out.println(entry.getClass());
        }

        //第三種
        System.out.println("通過Map.entrySet遍歷key和value");
        for(Map.Entry<String,String> entry:map.entrySet()){
            System.out.println("key= "+entry.getKey()+", value= "+entry.getValue());

        }

        //第四種
        System.out.println("通過Map.values遍歷所有的value,但不能遍歷key");
        for(String v:map.values()){
            System.out.println("value="+v);
        }
    }

}

執行結果:

通過Map.KeySet遍歷key和value:
key=1 and vlaue= value1
key=2 and vlaue= value2
key=3 and vlaue= value3
通過Map.entrySet使用iterator遍歷key和value:
key= 1, value= value1
key= 2, value= value2
key= 3, value= value3
通過Map.entrySet遍歷key和value
key= 1, value= value1
key= 2, value= value2
key= 3, value= value3
通過Map.values遍歷所有的value,但不能遍歷key
value=value1
value=value2
value=value3

參考博文:https://blog.csdn.net/Darry_R/article/details/78915420