Pergunta

I'm reading different keys and their corresponding keys from a textfile. I want to create a hashmap that takes in the keys and their corresponding keys. It needs to be accesible in both ways.

How do I do this?

I've managed to do it but it works only for the left side.

Foi útil?

Solução

As every country has only a few members I would do it with a map and just implement a method to update the state of each country in a pair of neighbours. If it was, however, a dense structure, i.e. every element had nearly all other as neighbours, I would recommend using an indicator matrix: rows and columns are countries and a true value on the intersection defines they are neighbours. But here goes the first solution, with a 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;
   }
}

Usage:

Countries countries = Countries.fromFile("path/to/file");

Outras dicas

Each map entry should contain a set of countries that borders it. Every country should have it's own Map entry

You can use a map of <String, Set<String>>

Where key is a country and the value is a set of neighbors. For each line, check if the country exists in the map, if it does, update its neighbor (add new neighbor in the set). If doesn't, create a new entry with value.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top