TLD
TLD

Reputation: 8135

Fast way to load all alphabetic characters to a hashmap

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?

Upvotes: 14

Views: 23156

Answers (5)

Suleman
Suleman

Reputation: 41

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

IntStream.rangeClosed((int) 'a', (int) 'z').forEach(ch -> map.put((char) ch, 0));

Upvotes: 0

jker
jker

Reputation: 465

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());
}

Upvotes: 0

rai.skumar
rai.skumar

Reputation: 10677

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.

Upvotes: 5

Samoth
Samoth

Reputation: 460

Try this:

Map<String,Integer> map = new HashMap<>();
for (int i = 65; i <= 90; i++) {
      map.put(Character.toString((char) i), 0);
}

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186823

Do it in for loop:

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

Upvotes: 27

Related Questions