Reputation: 8135
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
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
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
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
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
Reputation: 186823
Do it in for loop:
for (char ch = 'A'; ch <= 'Z'; ++ch)
map.put(String.valueOf(ch), 0);
Upvotes: 27