有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java打印地图的键和值

我用整型键创建了一个映射,值是字符串集。我已经用一些测试数据填充了映射,现在需要编写一个方法来打印映射的内容,比如“key:value,value,value”

我假设遍历映射,将键分配给一个int变量并将其打印出来是如何开始的,但是我接下来如何打印字符串集中的值呢

public class HandicapRecords {

    private Map<Integer, Set<String>> handicapMap;

    public HandicapRecords() {
        handicapMap = new HashMap<>();
    }

    public void handicapMap() {
        Set<String> players = new HashSet<>();

        players.add("Michael");
        players.add("Roger"); 
        players.add("Toby");
        handicapMap.put(10, players);

        players = new HashSet<>();
        players.add("Bethany");
        players.add("Martin");
        handicapMap.put(16, players);

        players = new HashSet<>();
        players.add("Megan");
        players.add("Declan");
        handicapMap.put(4, players);
    }

    public void printMap() {
        //code for method to go here
    }

}

共 (3) 个答案

  1. # 1 楼答案

    您可以像在列表中一样迭代Set数据结构(实际上,列表保留顺序,而集合不保留顺序,但我认为这超出了这个问题的范围)

    要打印数据,可以执行以下操作:

    for (Integer num : handicapMap.keySet()) {
            System.out.print("Key : " + String.valueOf(num) + " Values:");
            for (String player : handicapMap.get(num)) {
                System.out.print(" " + player + " ");    
            }
            System.out.println();
        }
    
  2. # 2 楼答案

    您为每个循环指定了嵌套。我们不能直接迭代HashMao,获取密钥集并打印。 例如:

    public void printMap()
    {
     Set<Integer> keys=handicapMap.keySet();
     for(Integer k:keys)
     {
         Set<String> players=handicapMap.get(k);
         System.out.print(" "+k+":");
         int i=0;
         for(String p:players)
         {
             i++;
             System.out.print(p);
             if(i!=players.size())
                 System.out.print(",");
         }
         System.out.println();
     }
    }
    
  3. # 3 楼答案

    我想您可能不知道密钥,因此必须迭代哈希映射中的所有条目:

    for (Map.Entry<Integer, Set<String>> entry : handicapMap.entrySet())
    {
        Integer key = entry.getKey();
        HashSet<String> values = entry.getValue();
    
        for (String s : values) { 
            // and now do what you need with your collection values
        }
    }