30

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.

52

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};
  • Cool, thanks to Daniel and Keith for the superfast edits :) – Phil Hawthorn Sep 29 '14 at 9:19
  • @Remario I'm not sure what you mean by that, your comment is confusing for people. Can you either delete or elaborate? – Phil Hawthorn Nov 4 at 20:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.