Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize and fill Map in Java 8?

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);
}
like image 814
bresai Avatar asked Mar 10 '23 07:03

bresai


1 Answers

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)));
like image 132
Eran Avatar answered Mar 19 '23 08:03

Eran