打印出地图的键和值



ive创建了一个带有类型整数键的地图,值是字符串集。我已经用一些测试数据填充了地图,现在需要编写一种方法,以打印出地图的内容,例如"键:值,值,值"

im假设通过地图进行迭代,并将键分配给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-each循环。我们无法直接通过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();
 }
}

我想您不会知道钥匙,因此您必须在Hash Map中的所有条目中迭代:

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

最新更新