I need to initialize a Map with 500 entries, and set each to 0. How to achieve that using Java 8?
Map<Integer, Integer> map = new HashMap<>(500);
for (int i = 0; i < 500; i++){
map.put(i,0);
}
The same code would work just fine in Java 8.
Other ways of doing the same thing :
Map<Integer,Integer> map = new HashMap<>(500);
IntStream.range(0,500).forEach(i -> map.put(i,0));
or
Map<Integer,Integer> map = IntStream.range(0,500).boxed().collect(Collectors.toMap(Function.identity(),i -> Integer.valueOf(0)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With