Initialize Map

Is there a way to initialize a Map<String, Integer> without using put method ?

I saw that for initalize a Map<String, String> :

private Map<String, String> myMap = new Map<String, String>('a' => 'John', 'b' => 'Mike', 'c' => 'Eddy');

But this doesn’t work with my map.

Answer

Simply change the round brackets:

private Map<String, String> myMap = new Map<String, String>('a' => 'John', 'b' => 'Mike', 'c' => 'Eddy');

To curly brackets (and change the values to integers):

private Map<String, Integer> myMap = new Map<String, Integer>{'a' => 1, 'b' => 2, 'c' => 3};

Attribution
Source : Link , Question Author : SF_user , Answer Author : Daniel Ballinger

Leave a Comment