有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在地图而不是列表上迭代

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

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

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

    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的一个实例” 怎么解决呢


共 (2) 个答案

  1. # 1 楼答案

    你需要使用result.entrySet()。返回一个Set<Entry<LocalDate, Long>>>,它是可编辑的(Map不是)

    您的循环如下所示:

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

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

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