Map<String,Integer> map = new HashMap<String,Integer>() {{
put("x", 1);
put("y", 2);
}}
This abuses the fact that a brace after a constructor invocation indicates the creation of an anonymous inner subclass, and the second brace indicates code to be executed at instantiation time. So this "double brace initialization" has become a Java idiom. Still pretty awful, I know.I'm not sure if anyone has been able to use generics and varargs to create a map generating static function, but it might be possible. Something like:
Map<String,Object> m = map("x", 1, "y", 2);
I think the trouble is with automatically extracting the key value types from the varargs array. I think I have seen the approach: Map<String,Object> m = map(kv("x", 1), kv("y", 2));
where kv would just create a key value pair. That way you can make the generics inference come out right.All of this does make a pretty good argument for Python, Ruby, Javascript, etc.
UPDATE: just found this:
http://nicolas.lehuen.com/index.php/post/2006/10/07/113-java...
// Example usage :
import static Literals.map;
Map<String,Integer> example = map("hello",1).map("world",2).map("!",3);
Pick your poison.Python, Lua, and JS all have syntactic sugar for maps, and I think it makes a really big difference. They're quite versatile. Lua's table.key -> table["key"] sugar for all string keys is particularly nice.
Arc has similar syntax shortcuts for hashes (but sticks with parentheses):
http://ycombinator.com/arc/tut.txt
arc> (let h (obj x 1 y 2)
(h 'y))
2 (set-macro-character
#\] (get-macro-character #\)))
;; Array syntax: [array-name array-references] is equivalent to
;; (aref array-name array-references)
(set-macro-character
#\[
#'(lambda (stream char)
(declare (ignore char))
(destructuring-bind (array-name &rest array-references)
(read-delimited-list #\] stream t)
`(aref ,array-name ,@array-references))))
;; Hash table syntax: #[hash-table hash-key &optional default] is
;; equivalent to (gethash hash-key hash-table &optional default)
(set-dispatch-macro-character
#\# #\[ #'(lambda (stream subchar arg)
(declare (ignore subchar arg))
(destructuring-bind (hash-name hash-key &optional (default nil))
(read-delimited-list #\] stream t)
`(gethash ,hash-key ,hash-name ,default)))) (h 'key) and (h 'key 'new-val)
That's not too bad syntax-wise. Or, taking a cue from actor languages: (h 'get 'key) and (h 'set 'key 'new-val)Syntactic sugar in languages is quite convenient, especially for things that are used a lot. Thought a lot of syntactic sugar (like in Perl) can ruin a language and it's readability.
Adding SS also adds to what you need to remember to use the language effectively (and to read other peoples' code), but a little bit of syntactic sugar can go a really long way.
val m = Map('name -> "Bob", 'age -> 30, 'color -> Colors.Red)