Search code examples
javadictionaryiterationtreemap

Iterate over a TreeMap of Objects (not Strings!!) in Java


I've got a Treemap of Servers:

TreeMap server_map = new TreeMap<String, Server>() ;

I'd like to iterate over the whole map to print all the servers. Using this kind of loop:

for (Map.Entry<String, Server> entry : server_map.entrySet())
{
    System.out.println(entry.getKey() + "/" + entry.getValue().foo);
}

This won't work, because there is an Unresolved compilation problem:

Type mismatch: cannot convert from element type Object to Map.Entry

Isn't there a possibility to iterate over a Treemap of servers?


Solution

  • Change the declaration to this:

    TreeMap<String, Server> server_map = new TreeMap<String, Server>() ;