Populating a hashmap with predefined values (java)

46.9k views Asked by At

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?

4

There are 4 answers

3
RNJ On BEST ANSWER

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");
}};
0
Ondřej Stašek On

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

2
kosa On

May be other way, List RC,AC,GH as value and T1 as key for hashmap, this way you can reduce number of entries in map.

0
Amit Deshpande On

You can use PropertiesConfiguration from apache commons.

value can contain value delimiters and will then be interpreted as a list of tokens. Default value delimiter is the comma ','. So the following property definition

key = This property, has multiple, values