Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative ways for hard-coding Map in Java?

Tags:

java

hashmap

I'm having a HashMap in my Java program consisting of around 200 -Key-Value-pairs which won't change during runtime and I am looking for a good way to initialize all the pairs. Currently I have a hard-coded method like this

private void initializeHashMap(){
    hashMap.put(1, "String1");
    hashMap.put(2, "String2");
    hashMap.put(3, "String3");
...}

for all the 200 pairs. Is that really good practice or is there another, better way maybe to read the data from another class or an external file?

like image 990
DocRobson Avatar asked Nov 09 '17 10:11

DocRobson


2 Answers

This is the perfect use case to consider a properties file. When you read the file, it gives you a handy map to play with it.

like image 142
Suresh Atta Avatar answered Sep 22 '22 00:09

Suresh Atta


An alternative which is worse in terms of readability but better in terms of concision (that I'll employ in personal projects but avoid in team work) would be to use an anonymous class that defines its key/values at instanciation :

Map<Integer,String> myMap = new HashMap<Integer,String>(){{
    this.put(1, "String1");
    this.put(2, "String2");
}};

Now you're not instantiating an HashMap anymore but an anonymous class that extends it. This anonymous class' definition contains an instance initializer block that will be executed after the constructor and will set up the desired key/values.

like image 35
Aaron Avatar answered Sep 22 '22 00:09

Aaron