Search code examples
javahashmaptranslate

how to input sentences into HashMap


I have a program that is supposed to translate English into a made-up language, like elvish.

my first idea was to use hashmaps but of course, I can't do,

map.get("Hello, I am human");

and have it check "Hello", "i", "am", "a", "human" and then translate that into "Hallo, ich bin ein Mensch" or "dragon, robot cat whale horse"

How can I do this?


Solution

  • I know it might not be exactly what you want, but this is how I approached this. There's likely a better way to do this (I'm thinking regex or something) but I don't know how to do that so this is the best I've got.

    • Gather the input sentences
    • Split up the words
    • If the word is in the conversion map:
    • Retrieve the converted word and add to an array

      ArrayList<String> strings = new ArrayList<>(Arrays.asList("hello world", "this is a test"));
      HashMap<String, String> map = new HashMap<>();
      
      map.put("hello", "wordForHello");
      map.put("world", "wordForWorld");
      map.put("this", "wordForThis");
      map.put("is", "wordForIs");
      map.put("a", "wordForA");
      map.put("test", "wordForTest");
      
      ArrayList<String> sentence = new ArrayList<>();
      
      for (String str : strings) {
          String[] words = str.split(" ");
          for (String word : words) {
              if (map.containsKey(word)) {
                  sentence.add(map.get(word));
              }
          }
          System.out.println(sentence);
          sentence = new ArrayList<>();
      }