首页 > 解决方案 > 遍历地图而不是列表

问题描述

我呈现结果的代码如下所示:

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

但我想返回一个哈希图而不是一个列表,所以我希望它是这样的:

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

但后来我得到这个错误:“只能迭代数组或java.lang.Iterable的实例”如何解决?

标签: javalisthashmapconverters

解决方案


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

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

推荐阅读