Java traverses the Map collection to obtain key, value, etc.

First build a Map collection:

 Map<String, Integer> buy=new HashMap<>();
        buy.put("苹果手机", 2);//添加键值对
        buy.put("智能手表", 1);
        buy.put("java书", 1);
        buy.put("c语言书", 1);
        buy.put("西瓜", 2);

Print collection:
insert image description here

1. Only need to get key or value

1. Get the key:

  for (String key : buy.keySet()) {
    
    
            System.out.println(key);
        }

result:
insert image description here

2. Get value:

 for (Integer value :buy.values()) {
    
    
            System.out.println(value);
        }

result:
insert image description here

2. Obtain key and value at the same time:

1. Obtain the value through get(key) of keySet

 for (String key : buy.keySet()) {
    
    
   System.out.println(key + ":" + buy.get(key));
      }

Result:
insert image description here
2. Traverse through entrySet

  for (Map.Entry<String, Integer> entry : buy.entrySet()) {
    
    
 System.out.println(entry.getKey() + ":" + entry.getValue());
        }

insert image description here
3. Traverse through Lambda expression

 buy.forEach((key,value)->{
    
    
           System.out.println("key:"+key+"value"+value);
        });

Result:
insert image description here
4. Traverse through the iterator Iterator

The above traversal methods all use the enhanced for loop——foreach, which is a feature only available since JDK 5.
Although the operation of foreach looks very simple, it has a disadvantage: when traversing the Map, if its size is changed, the A concurrent modification exception will be thrown. But if you only need to delete elements in the Map during traversal, you can use the remove() method of Iterator to delete elements: , the
example here is to delete the element whose key is watermelon:

Iterator<Map.Entry<String, Integer>> it = buy.entrySet().iterator();
        while (it.hasNext()) {
    
    
            Map.Entry<String, Integer> entry = it.next();
            if (entry.getKey().equals("西瓜")) {
    
    
                it.remove();
            }
        }
        System.out.println(buy);

Results:
insert image description here
Summary:
(1) 如果只获取 key 或者 value, 推荐使用 keySet() 或 values() 方法;
(2) 如果需要同时获取 key 和value, 推荐使用 entrySet;
(3) 如果需要在遍历过程中删除元素, 推荐使用 Iterator;
(4)如果需要在遍历过程中添加元素, 可以新建一个临时 Map 存放新增的元素, 遍历结束后, 再把临时 Map 添加到原 Map 中.

Reference link: 5 ways to traverse Map in Java

Guess you like

Origin blog.csdn.net/weixin_42260782/article/details/130982522