• Map的遍历


    Map是我们常用的数据容器,常用的有以下几种遍历方式,代码如下:

     1 package Map;
     2 
     3 import java.util.*;
     4 
     5 /**
     6  * @author o_0sky
     7  * @date 2019/2/15 0:37
     8  */
     9 public class MapTest {
    10     public static void main(String[] args) {
    11         Map<Integer, String> map = new HashMap<Integer, String>();
    12         map.put(1, "a");
    13         map.put(2, "b");
    14         map.put(3, "c");
    15     }
    16 
    17     //①通过Map.keyset遍历key和value
    18     private static void method1(Map<Integer, String> map) {
    19         Set<Integer> set1 = map.keySet();
    20         for (Integer key1 : set1) {
    21             String value1 = map.get(key1);
    22             System.out.println("key" + "=" + key1 + "," + "value" + "=" + value1);
    23         }
    24     }
    25 
    26     //②通过Map.entrySet使用迭代器遍历key和value
    27     private static void method2(Map<Integer, String> map) {
    28         //生成迭代器
    29         Set<Map.Entry<Integer, String>> set2 = map.entrySet();
    30         Iterator<Map.Entry<Integer, String>> it = set2.iterator();
    31         while (it.hasNext()) {
    32             Map.Entry<Integer, String> entry = it.next();
    33             Integer key2 = entry.getKey();
    34             String value2 = entry.getValue();
    35             System.out.println("key" + "=" + key2 + "," + "value" + "=" + value2);
    36         }
    37     }
    38 
    39     //③通过Map.entrySet遍历key和value
    40     private static void method3(Map<Integer, String> map) {
    41         Set<Map.Entry<Integer, String>> set3 = map.entrySet();
    42         for (Map.Entry<Integer, String> entry : set3) {
    43             Integer key3 = entry.getKey();
    44             String value3 = entry.getValue();
    45             System.out.println("key" + "=" + key3 + "," + "value" + "=" + value3);
    46         }
    47     }
    48 
    49     //④直接通过Map.values遍历所有的value,但不能遍历key
    50     private static void method4(Map<Integer, String> map) {
    51         Collection<String> values = map.values();
    52         for (String value : values) {
    53             System.out.println("value" + "=" + value);
    54         }
    55     }
    56 }
  • 相关阅读:
    spring aop实现过程之三Spring AOP中Aspect编织的实现
    spring aop实现过程之一代理对象的生成
    数据库常用面试题(SQL Server) (转载)
    回溯法解八后问题
    masmplus增加调试工具
    c++ new关键字 详解
    EMU8086 编译器使用简介
    汇编操作显存
    回溯法简介
    汇编链接时 错误:unresolved external symbol _WinMainCRTStartup
  • 原文地址:https://www.cnblogs.com/linsky/p/10381480.html
Copyright © 2020-2023  润新知