JAVA:从 Hashmap 返回所有键值

标签 java arrays list iterator hashmap

我即将编写一些代码来管理“虚拟”火车/地铁站网络。我已经使用 Map (String), (List)(String) 类型的 Map 实现了它。最后一种方法(我现在正在努力使用的方法)应该返回所有已添加到网络中的“站”,而不重复。我现在正试图让这些值返回,但是对这两个问题的任何建议都将不胜感激。我在下面介绍了我是如何设置 map 的,以及所讨论的方法。理想情况下,我希望这些值作为数组返回,但编译器似乎对我的语法有一些疑问。再次感谢!

public class MyNetwork implements Network {

Map<String, List<String>> stations = new HashMap<>();

@Override
public String[] getStations() {
 /**
 * Get all stations in the network.
 * @return An array containing all the stations in the network, with no
 * duplicates.
 */

return stations.toArray(new String[0]);

}

最佳答案

参见 keySet() map 的方法,更进一步,请参阅 toArray()集合法。

一个小的代码示例看起来像这样:

public String[] getStations() {
        /* the reason you need to give the new String array to the toArray() method is, 
        so that the compiler knows that it is in fact an array of String, not just plain array of object */
        return stations.keySet().toArray(new String[0]);
}

关于JAVA:从 Hashmap 返回所有键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21811872/

相关文章:

java - 无法使用 hasNext 跳出循环

python - 在 python 中,len(list) 是做什么的?

java - immutableList 但仍然可以修改列表中的元素

java - 从Java中的文本文件中读取数据作为数组

java - 如何在 Eclipse 中创建 Java 方法描述?

java - 哪条路是最好的路?使用 null 重复 VS

java - 如何在 Java 中使用枚举作为数组下标

java - 如何从 Java 应用程序制作医学摘要文件

arrays - 如果安装了 intarray 扩展,Postgres 不会在整数数组上使用索引

Perl:展平多维数组的最简单方法是什么?