The way to traverse the map in java

The following mainly introduces the use of the new feature of JDK1.5 For-Each loop in java to traverse the Map collection to solve some problems.

Map collection : It is stored in the way of key-value key-value pair mapping. The key is unique in the Map, but the value can be repeated. One key corresponds to one value. The key is unordered and unique, while the value is unordered and not unique

One, use the keySet collection

According to the characteristics of the Map collection, we can know that the key in the map is unique. So we can use the keySet in the map to traverse. The detailed code is as follows:

    public static void main(String[] args) {
    
    
        Map<Integer, String> map = new HashMap<>();
        map.put(1,"one");
        map.put(2,"two");
        map.put(3,"three");

        //方式一:利用keySet()
        Set<Integer> set = map.keySet();
        for (Integer key:map.keySet()
             ) {
    
    
            System.out.println(map.get(key));
        }
    }

According to the code, it can be seen map.keySet();that what is returned is a Set collection composed of keys in the map collection.

Second, use values ​​to traverse

In this way, the value value can be traversed without using the key value. The specific code is as follows:

    public static void main(String[] args) {
    
    
        HashMap<Integer, String> map = new HashMap<>();
        map.put(1,"one");
        map.put(2,"two");
        map.put(3,"three");

        //方式二:
        for (String value:map.values()
             ) {
    
    
            System.out.println(value);
        }
    }

Third, use Map.entrySet to traverse key and value (the most commonly used and most important method)

Use the internal interface that comes with the Map interface Entry<K , V>to perform excessive traversal. The Map.entrySet method obtains a collection of all key-value objects. The specific code is as follows:

method name illustrate
Set<Map.Entry<K,V>> entrySet() Get a collection of all key-value pair objects
K getKey() get key
V getValue() get value
    public static void main(String[] args) {
    
    
        HashMap<Integer, String> map = new HashMap<>();
        map.put(1,"one");
        map.put(2,"two");
        map.put(3,"three");
        //方式三:
        for (Map.Entry<Integer,String> ma:map.entrySet()
             ) {
    
    
            System.out.println(ma.getKey()+"===="+ma.getValue());
        }
    }

Guess you like

Origin blog.csdn.net/qq_44085437/article/details/125833164