Populating a hashmap with predefined values (java)

37,121

Solution 1

I would do the initialisation while setting up the HashMap

For example

private static final Map<String, String> m = new HashMap<String, String>() {{
    put("RC", "T1");
    put("AC", "T1");
}};

Then you wuld make sure that everything is set up together in your code.

I think @Nambari makes a good point though with perhaps having the value as a list rather than just a string. This does then swap your keys and values though.

eg

 private static final Map<String, List<String>> m = new HashMap<String, List<String>>() {{
    put("T1", Arrays.asList("RC", "AC");
}};

Solution 2

With Java 11 you can use Map.of("RC", "T1", "AC", "T1");

Share:
37,121
user1652875
Author by

user1652875

Updated on August 28, 2021

Comments

  • user1652875
    user1652875 almost 3 years

    I've run into a problem I haven't had to deal with before. I'm writing a patch for a database in java that's basically converting data stored in certain rows. In order to do this I have a conversion table that tells me what values become what.

    Example, if I read in either "RC", "AC", "GH" -> Update the value to "T1". (These are just random examples, it's basically converting one string to another.)

    I need a good way of storing these conversions. I was thinking a hashmap: KEY,VALUE: (RC,T1) (AC,T1) (GH,T1) and so on and so on.

    Now, there's dozens and dozens of these. What's a good clean way of populating this hashmap when the patch initializes?

  • Marc Bredt
    Marc Bredt almost 12 years
    But, complexity of a lookup in such structure won't be any good - how would you search such map then, say when looking up for a replacement for "RC"?
  • kosa
    kosa almost 12 years
    I agree, this is simple approach if you have less keys (like T1,T2 etc.,). If less keys you can get entrySet() and play with it. If number of keys also high, then lookup time would be high. Again, it is trade-off, simplicity at one place creates complexity on other end.
  • user1652875
    user1652875 almost 12 years
    Thanks! That's kind of what I was thinking (your first example). I was hoping there might be a really tidy way of doing it but I guess I'm going to have to get down and dirty. Greatly appreciated RNJ for confirming.
  • RNJ
    RNJ almost 12 years
    @user1652875 I think it's slightly tidier having the initialisation in the same place as the declaration. Then you know for sure the map does contain some data.
  • MC Emperor
    MC Emperor about 5 years
    Warning: Do not use the "double brace initializer", it creates an anonmous subclass of HashMap, which may potentially result in a performance hit. Second, this is confusing to the reader, since this code suggests that there is some "double brace initializer" construct, while there is none.