I'm currently working on an Android app and I need to translate keys of type String to Integers which are determined at compile time of R.raw.
Right now I have found two ways of creating such a Map that holds all (needed) values of R.raw:

private static final Map<String, Integer> map = ImmutableMap.<String, Integer>builder()
                                                .put("...", R.raw.id)


private static final Map<String, Integer> map = new ArrayMap<>();
static {
    map.put("...", R.raw.id);

My questions are:

  • Are there better ways of creating a Map to lookup keys and return values that are determined at compile time? I don't want to use reflection.
  • Which one of those ways would you prefer?
  • 1
    \$\begingroup\$ Because you are mentioning raw, I would suggest placing your files in assets folder, you can reference them by filename from the AssetManager. Then you can just use a List of Strings and you don't need to create a Map. \$\endgroup\$ Jul 11, 2015 at 13:09
  • \$\begingroup\$ @user1281750 you might add this as an answer. \$\endgroup\$
    – GiantTree
    Jul 11, 2015 at 22:27

1 Answer 1


There is not such thing as ArrayMap in standard Java. Therefore, I am just going to assume that you meant HashMap.

I would choose neither of those options. Depending on how many elements you need to insert into that Map, you could end up with a big chunk of code that is just a group of add calls.

I recommend creating two arrays: one of the Strings, and one of the Integers.

Then, all you have to do is create a loop that inserts all the values into the map.

Here is what I came up with:

String[] foos = {...};
Integer[] bars = {...};
Map<String, Integer> map = new HashMap<String, Integer>();

for(int i = 0, length = foo.length; i < length; i++) {
    map.put(foos[i], bars[i]);
  • \$\begingroup\$ ArrayMap is a more memory efficient HashMap designed for Android. I'm currently checking user1281750's approach, but your's might come in handy, when you can't move resources to assets (in Android). \$\endgroup\$
    – GiantTree
    Jul 11, 2015 at 22:26
  • \$\begingroup\$ @GiantTree Ah, I see. I was wondering where ArrayMap was coming from (I am not experienced with Android). \$\endgroup\$
    – SirPython
    Jul 11, 2015 at 22:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.