简体   繁体   English

在Java中遍历对象的TreeMap(不是字符串!)

[英]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 类型不匹配:无法从元素类型Object转换为Map.Entry

Isn't there a possibility to iterate over a Treemap of servers? 是否有可能遍历服务器的树形图?

将声明更改为此:

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

还要注意,由于java7不需要在右侧声明泛型类型,因此可以使用菱形运算符,从而节省了一些编写工作。

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

In Java 8 you can do it this way: 在Java 8中,您可以这样进行:

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. 如果使用<String, Server>方式,它将希望您使用Java 1.5语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM