Advanced JAVA - Traversal methods and common APIs for Map series collections

Table of contents

        1.0 Description of Map collection

        1.1 Common methods of Map collection

        1.2 Characteristics of Map series collections

        ​ ​ 2.0 Traversal methods for Map series collections (three methods)

         ​​​​​ 2.1 Use keySet() method to traverse

        ​ ​ 2.2 Use the entrySet() method to traverse

        ​ ​ 2.3 Traversing using the forEach() method (Java 8+)


        1.0 Description of Map collection

        Map is a collection type used to storekey-value pairs( key-value pairs). Each key is unique, while values ​​can be repeated. Map can quickly find the corresponding value based on the key. In a Map keys and values ​​can be objects of any type. Simply put, the Map class is an interface and a container that stores elements of key-value pair type.

        1.1 Common methods of Map collection

Introduce in code Map Common methods of collection:

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MapAPI {
    public static void main(String[] args) {
        //由于 Map 是一个接口,不能直接 new 一个 Map 类型的对象,
        //所以需要用到 Map 的实现类 HashMap 来创建对象。

        Map<String,Integer> map = new HashMap<>();//一行经典代码

        //1. put(k,v) :实例方法,添加元素
        map.put("二哈",250);
        map.put("金毛",750);
        map.put("拉布拉多",1250);
        map.put("中华田园犬",1359);
        System.out.println(map);
    //输出结果为:{二哈=250, 金毛=750, 中华田园犬=1359, 拉布拉多=1250}

        //2. size() :实例方法,获取元素大小
        int s = map.size();
        System.out.println(s);
        //输出结果为:4

        //3. isEmpty() :实例方法,判断集合是否为空,为空返回true,反之
        boolean b = map.isEmpty();
        System.out.println(b);
        //输出结果为:false

        //4. get(k) :实例方法,根据键获取对应的值
        int i = map.get("二哈");
        System.out.println(i);
        //输出结果为:250

        //5. remove(k) :实例方法,根据键删除整个元素
        map.remove("二哈");
        System.out.println(map);
        //输出结果为:{金毛=750, 中华田园犬=1359, 拉布拉多=1250}

        //6. containsKey(k) :实例方法,判断是否包含某个键
        boolean bk = map.containsKey("二哈");
        System.out.println(bk);
        //输出结果为:false

        //7. containsValue(k) :实例方法,判断是否包含某个值
        boolean bv = map.containsValue(750);
        System.out.println(bv);
        //输出结果为:true

        //8. keySet() :实例方法,获取全部键的集合,
        // 需要用 Set 系列集合来接受。
        Set<String> stringSet = map.keySet();
        System.out.println(stringSet);
        //输出结果为:[金毛, 中华田园犬, 拉布拉多]

        //9. values() :实例方法,获取全部值
        //需要用 Collection 系列集合来接受
        Collection<Integer> collection = map.values();
        System.out.println(collection);
        //输出结果为:[750, 1359, 1250]

        //10. putAll(Map m) :将 m 中的内容全部倒入到调用该方法的集合中。
        Map<String,Integer> map1 = new HashMap<>();
        map1.put("小黑",19999);
        map1.put("小白",29999);
        map.putAll(map1);
        System.out.println(map);
  //输出结果为:{小白=29999, 金毛=750, 小黑=19999, 中华田园犬=1359, 拉布拉多=1250}

        //11. clear() :实例方法,删除整个集合中的元素
        map.clear();
        System.out.println(map);
        //输出结果为:{}

    }
}

The running results are as follows:

        1.2 Characteristics of Map series collections

        Unordered: means that it will not be output according to the added elements, but will be output randomly, as follows:

        Non-repeatable: The "key" specified is not allowed to appear repeatedly. Repeated elements added later will overwrite the elements with the same "key", but the "value" is not allowed. Make a request and it can appear repeatedly, such as the following:

        No index:Because the Map series collection does not support a fixed order, the existence of an index is naturally meaningless.

        ​ ​ 2.0 Traversal methods for Map series collections (three methods)

         ​​​​​ 2.1 Use keySet() method to traverse

        Get all through the keySet() method of Map keys, then use for-each to loop through the keys and pass get() Method to obtain the corresponding value.

This is achieved through specific code:

public class MapIteration {
    public static void main(String[] args) {

        Map<String,Integer> map = new HashMap<>();
        map.put("二哈",250);
        map.put("金毛",1250);
        map.put("拉布拉多",2250);
        map.put("中华田园犬",3250);

        //先取出该集合的全部”键“
        Set<String> stringSet = map.keySet();
        //然后用增强 for 方法根据”键“通过 get(k) 来查询”值“
        for (String k:stringSet) {
            int v = map.get(k);
            System.out.println(k+"=="+v);
        }
    }
}

operation result:

        Step: First remove all the "keys" of the collection, and then useto enhance the for methodAccording to the "key" pass get(k) method to query "value".

        ​ ​ 2.2 Use the entrySet() method to traverse

        Get all through Map ’s entrySet() method Entry object of key-value pairs, and then use for-each loop TraverseEntry objects,. To put it simply, consider a key-value pair in the collection as a whole, and then use the enhancedfor loop to traverse the collection, and then passfor The a> methods get the key and value. getValue() and getKey()

This is achieved through specific code:

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MapIteration {

    public static void main(String[] args) {
        Map<String,Integer> map = new HashMap<>();
        map.put("二哈",250);
        map.put("金毛",1250);
        map.put("拉布拉多",2250);
        map.put("中华田园犬",3250);

        //通过调用 map 的实例方法 entrySet(),键值对包装成一个整体,
        //Map.Entry<String,Integer>这代码可以理解为是一个类型,用 Set 系列集合来存储
        Set<Map.Entry<String,Integer>> entrySet = map.entrySet();
        for (Map.Entry<String,Integer> entry:entrySet) {
            String k = entry.getKey();
            int v = entry.getValue();
            System.out.println(k+"=="+v);
        }
    }
}

The running result is:

        ​ ​ 2.3 Traversing using the forEach() method (Java 8+)

        Pass Map ’s forEach() method, pass Enter a BiConsumer function interface to traverse key-value pairs. BiConsumer interface’s accept() method receives two parameters, namely keys and values.

        It should be noted that here forEach() theMap instance method.

This is achieved through specific code:

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

public class MapIteration {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("二哈", 250);
        map.put("金毛", 1250);
        map.put("拉布拉多", 2250);
        map.put("中华田园犬", 3250);
/*        map.forEach(new BiConsumer<String, Integer>() {
            @Override
            public void accept(String k, Integer v) {
                System.out.println(k+"=="+v);
            }
        });*/
        
        //进一步简化为:
        map.forEach((k, v) -> System.out.println(k + "==" + v));
    }
}

The running results are as follows:

        Additionally, in fact, this method is essentially a packaging of the second method. The essence is to use the entrySet() method to traverse. The source code is as follows:

        It can be seen that the third method is very easy to implement the traversal of the Map series collection, and it only requires one line of code. Easy to remember:

map.forEach((k, v) -> System.out.println(k + "==" + v));

         This article will be introduced here first. For more information, click the following link:  Xiaopu_-CSDN Blog 



Guess you like

Origin blog.csdn.net/Tingfeng__/article/details/133993687