YMMD
YMMD

Reputation: 3780

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?

Upvotes: 0

Views: 1689

Answers (3)

user3709559
user3709559

Reputation: 11

In Java 8 you can do it this way:

TreeMap server_map = new TreeMap();
for (Map.Entry entry : server_map.entrySet()){
 System.out.println(entry.getKey() + "/" + ((Server)entry.getValue()).foo);
}

I just solved a problem similar to this one by doing something like this. If you use the <String, Server> way it will want you to use java 1.5 syntax.

Upvotes: 0

arynaq
arynaq

Reputation: 6870

Also note that since java7 you do not need to declare the generic type on the right-hand-side, you can use the diamond-operator, saves some writing.

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

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 360046

Change the declaration to this:

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

Upvotes: 3

Related Questions