13

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
  • 180,369
  • 20
  • 160
  • 215
Xitrum
  • 7,765
  • 26
  • 90
  • 126

5 Answers5

26

Do it in for loop:

for (char ch = 'A'; ch <= 'Z'; ++ch) 
  map.put(String.valueOf(ch), 0); 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
5

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.

rai.skumar
  • 10,309
  • 6
  • 39
  • 55
1

Try this:

Map<String,Integer> map = new HashMap<>();
for (int i = 65; i <= 90; i++) {
      map.put(Character.toString((char) i), 0);
}
Samoth
  • 460
  • 1
  • 11
  • 30
  • 1
    ASCII codes (65 and 90) are quite unreadable (magic numbers); better to use char: for(char i = 'A'; i <= 'Z'; ++i) etc – Dmitry Bychenko Feb 25 '14 at 09:41
  • @DmitryBychenko Can elaborate or give a link to what you mean by magic number in this context? – Subir Kumar Sao Feb 25 '14 at 09:46
  • @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 http://en.wikipedia.org/wiki/Magic_number_%28programming%29 – Marco13 Feb 25 '14 at 09:49
  • @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"?). http://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad – Dmitry Bychenko Feb 25 '14 at 09:50
0

With io.vavr

public HashMap<String,Integer> alphanumericAlphabet() {
    return CharSeq
            .rangeClosed('0','9')
            .appendAll(CharSeq.rangeClosed('a','z'))
            .appendAll(CharSeq.rangeClosed('A','Z'))
            .map(character ->Tuple.of(
                    character.toString(),
                    Character.getNumericValue(character)
            ))
            .collect(HashMap.collector());
}
jker
  • 465
  • 3
  • 13
0

Use an IntStream to add char's to a map:

IntStream.rangeClosed((int) 'a', (int) 'z').forEach(ch -> map.put((char) ch, 0));
Juan Diego Lozano
  • 989
  • 2
  • 18
  • 30
Suleman
  • 41
  • 2