【问题标题】:Map<String, String>, how to print both the "key string" and "value string" together [duplicate]Map<String, String>,如何同时打印“键字符串”和“值字符串”[重复]
【发布时间】:2016-06-09 02:58:42
【问题描述】:

我是 Java 新手,正在尝试学习地图的概念。

我想出了下面的代码。但是,我想同时打印出“key String”和“value String”。

ProcessBuilder pb1 = new ProcessBuilder();
Map<String, String> mss1 = pb1.environment();
System.out.println(mss1.size());

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

我只能找到只打印“关键字符串”的方法。

【问题讨论】:

  • System.out.println(key + ", " + mss1.get(key) );
  • 一个带有 apache.commons.lang.StringUtils 的衬垫:String message = StringUtils.join(yourMap.entrySet().toArray(), "\n");

标签: java dictionary key


【解决方案1】:

在循环内部,您拥有密钥,您可以使用该密钥从 Map 中检索值:

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

【讨论】:

    【解决方案2】:
    final Map<String, String> mss1 = new ProcessBuilder().environment();
    mss1.entrySet()
            .stream()
            //depending on how you want to join K and V use different delimiter
            .map(entry -> 
            String.join(":", entry.getKey(),entry.getValue()))
            .forEach(System.out::println);
    

    【讨论】:

      【解决方案3】:

      有多种方法可以实现这一目标。这是三个。

          Map<String, String> map = new HashMap<String, String>();
          map.put("key1", "value1");
          map.put("key2", "value2");
          map.put("key3", "value3");
      
          System.out.println("using entrySet and toString");
          for (Entry<String, String> entry : map.entrySet()) {
              System.out.println(entry);
          }
          System.out.println();
      
          System.out.println("using entrySet and manual string creation");
          for (Entry<String, String> entry : map.entrySet()) {
              System.out.println(entry.getKey() + "=" + entry.getValue());
          }
          System.out.println();
      
          System.out.println("using keySet");
          for (String key : map.keySet()) {
              System.out.println(key + "=" + map.get(key));
          }
          System.out.println();
      

      输出

      using entrySet and toString
      key1=value1
      key2=value2
      key3=value3
      
      using entrySet and manual string creation
      key1=value1
      key2=value2
      key3=value3
      
      using keySet
      key1=value1
      key2=value2
      key3=value3
      

      【讨论】:

      • 使用 Map.Entry 代替 Entry
      猜你喜欢
      • 2017-01-26
      • 2012-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-16
      • 1970-01-01
      • 2012-04-14
      相关资源
      最近更新 更多