我创建了一个包含整数类型键的映射,值是字符串集。我用一些测试数据填充了地图,现在需要编写一个打印出地图内容的方法,如“key:value,value,value”
我假设迭代遍历地图,并将键分配给int变量并将其打印出来是如何开始的,但是我将如何打印字符串集中的值呢?
FORM
答案 0 :(得分: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();
}
答案 1 :(得分:1)
你使用嵌套for-each循环。我们无法直接遍历HashMao,取得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();
}
}
答案 2 :(得分:0)
我猜你不会知道密钥,所以你必须迭代哈希映射中的所有条目:
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
}
}