打印出地图的键和值

Print out keys and values of a map

我创建了一个映射,其键类型为整数,值是字符串集。我已经用一些测试数据填充了地图,现在需要编写一个方法来打印出地图的内容,例如 "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
    }

}

您可以像在列表中那样对 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();
    }

我猜你不知道密钥,所以你必须遍历哈希映射中的所有条目:

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
    }
}

您使用了嵌套的 for-each 循环。我们不能直接遍历 HashMap,拿 keySet 打印。 示例:

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();
 }
}