-1

My code for presenting results looks like this:

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

But I want to return a hashmap instead of a list so I want it to be like this:

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

But then I get this error: "Can only iterate over an array or an instance of java.lang.Iterable" How can it be solved?

Natalie_94
  • 79
  • 3
  • 12

3 Answers3

0

I think you're asking how to iterate a map, instead of list. You can iterate the map like this:

for (Map.Entry<LocalDate, Long> entry : result.entrySet()) {
    System.out.println(entry.getKey() + " " + entry.getValue());
}
Oleksi
  • 12,947
  • 4
  • 56
  • 80
0

You need to use result.entrySet(). That returns a Set<Entry<LocalDate, Long>>>, which is iterable (Map isn't).

Your loop would look like this:

for (Entry<LocalDate, Long> s : result.entrySet()) {
    System.out.println(s.getKey() + " - " + s.getValue());
}
Nicktar
  • 5,548
  • 1
  • 28
  • 43
0

You should use entrySet of map.

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