Fast way to load all alphabetic characters to a hashmap

14,942

Solution 1

Do it in for loop:

for (char ch = 'A'; ch <= 'Z'; ++ch) 
  map.put(String.valueOf(ch), 0); 

Solution 2

Use double brace initialization. It's very compact and helpful in initializing collections.

Map<String, Integer> map = new HashMap<String, Integer>() {
        {
            for (char ch = 'A'; ch <= 'Z'; ++ch) 
                put(String.valueOf(ch), 0); 
        }
};

Note that - put method is called without the map reference.

Solution 3

Try this:

Map<String,Integer> map = new HashMap<>();
for (int i = 65; i <= 90; i++) {
      map.put(Character.toString((char) i), 0);
}
Share:
14,942
Xitrum
Author by

Xitrum

merge me

Updated on July 02, 2022

Comments

  • Xitrum
    Xitrum about 2 years

    For example I have this Hashmap:

    Map<String,Integer> map = new HashMap<>();
    

    Instead of doing map.put("A",0), map.put("B",0)... until map.put("C",0), is there any way we can make it fast?

  • Dmitry Bychenko
    Dmitry Bychenko over 10 years
    ASCII codes (65 and 90) are quite unreadable (magic numbers); better to use char: for(char i = 'A'; i <= 'Z'; ++i) etc
  • Subir Kumar Sao
    Subir Kumar Sao over 10 years
    @DmitryBychenko Can elaborate or give a link to what you mean by magic number in this context?
  • Marco13
    Marco13 over 10 years
    @Subir Kumar Sao A "magic number" is a fixed number in the source code, without an explaination why this particular number was used. In this example: What is "65"? Why not "66"? Also see en.wikipedia.org/wiki/Magic_number_%28programming%29
  • Dmitry Bychenko
    Dmitry Bychenko over 10 years
    @Subir Kumar Sao: When I say that "65" and "90" are "magic numbers" I mean that it's not evident what do they mean (what's "90"?). stackoverflow.com/questions/47882/…