我正在从文本文件中读取不同的键及其相应的键。 我想创建一个包含键及其对应键的 HashMap 。它需要能够以两种方式访问。
我该怎么做?
我已经成功做到了,但它只适用于左侧。
最佳答案
由于每个国家只有几个成员,我会用 map 来实现,并实现一种方法来更新两个邻国中每个国家的状态。然而,如果它是一个密集的结构,即每个元素几乎都有其他元素作为邻居,我建议使用指示矩阵:行和列是国家,交集上的真实值定义它们是邻居。但这是第一个解决方案,带有 map :
public class Countries
{
private final Map<String, Set<String>> countries = new HashMap<String, Set<String>>();
public void addCountry(@NotNull String name) {
addNeighbourPair(name, null);
}
public void addNeighbourPair(@NotNull String first, String second) {
if (!hasCountry(first)) {
countries.put(first, new HashSet<String>());
}
if (second != null) {
if (!hasCountry(second)) {
countries.put(second, new HashSet<String>());
}
countries.get(first).add(second);
countries.get(second).add(first);
}
}
public boolean hasCountry(String name) {
return countries.containsKey(name);
}
public Set<String> getNeighbours(String name) {
return countries.get(name);
}
/*
* the correctness of this loader is validated only with respect
* to using the Countries class :)
*/
public static Countries fromFile(String borders) {
Countries countries = new Countries();
Scanner bordersload = new Scanner(new File(borders));
while (bordersload.hasNextLine()) {
String line = bordersload.nextLine();
String[] values=line.split(" : |:|: | :");
String key=String.valueOf(values[0]);
String key1=String.valueOf(values[1]);
countries.addNeighbourPair(key, key1);
}
bordersload.close();
return countries;
}
}
用法:
Countries countries = Countries.fromFile("path/to/file");
关于java - 具有多个值的键可以通过两种方式访问JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23561879/