遍历地图而不是列表

iterate over a map instead of a list

我用于显示结果的代码如下所示:

    private void presentResult(List<Long> result) {
    if(result.size() == 0) {
        System.out.println("No matching values for the provided query.");
    }       
    for(String s : result) {
        System.out.println(s);
    }
}

但我想要 return 哈希图而不是列表,所以我希望它是这样的:

    private void presentResult(Map<LocalDate, Long> result) {
    if(result.size() == 0) {
        System.out.println("No matching values for the provided query.");
    }       
    for(Map<LocalDate, Long> s : result) {
        System.out.println(s);
    }
}

但是我得到这个错误:"Can only iterate over an array or an instance of java.lang.Iterable" 如何解决?

我想你问的是如何迭代地图,而不是列表。您可以像这样迭代地图:

for (Map.Entry<LocalDate, Long> entry : result.entrySet()) {
    System.out.println(entry.getKey() + " " + entry.getValue());
}

您需要使用 result.entrySet()。 returns 一个 Set<Entry<LocalDate, Long>>>,它是可迭代的(Map 不是)。

你的循环看起来像这样:

for (Entry<LocalDate, Long> s : result.entrySet()) {
    System.out.println(s.getKey() + " - " + s.getValue());
}

你应该使用地图的entrySet。

for(Map.Entry<LocalDate, Long> s : result.entrySet) 
{ 
    System.out.println(s.getKey()); 
    System.out.println(s.getValue());
}