java - 具有多个值的键可以通过两种方式访问​​JAVA

标签 java hashmap key-value

我正在从文本文件中读取不同的键及其相应的键。 我想创建一个包含键及其对应键的 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/

相关文章:

c# - 如果覆盖它,是否要求子类调用 super.doSomething()?

java - 向 Scoreloop 提交较小的结果

java - 处理 Lambda 表达式中的异常

java - 用于以下场景的最佳数据结构(如 HashMap /列表等)是什么

ios - 包含 NSNull 值的集合的键值编码和集合运算符

Java - 将图像拆分为 4 个图像

java - 如何强制HashMap使用identity(哈希码)?或建议解决方法

java - 无法调用该方法或更改 HashMap 中的值

ruby-on-rails - 按商店搜索和分组产品 REDIS

ios - 在 Xcode 中创建和编辑 plist 文件的步骤