2

I am looking for a Map-like collection that would allow me to create new object in a PHP/Python/JavaScript way:

var foo = new Foo({'foo': 'bar'})

The closest I have in Java is HashMap:

Map<String, String> parameters = new HashMap<String, String>();
parameters.put("test", "one two");
parameters.put("foo", "bar");

This is too verbose for my purpose. I would like to write down and handle over key-value pairs in an easier way.

I welcome any suggestions - creating own type of collection, creating own factory for a Map object etc. I just want to axe number of characters needed to write down to create such a collection.

Ondřej Mirtes
  • 5,054
  • 25
  • 36

2 Answers2

3

You have the (not very well-known) double brace initialization trick:

Map<String, String> Map = new HashMap<String, String>() {{
      put("test", "one two");
      put("foo", "bar");
}};

With java 7 diamond operator this is even more succinct, see:

Map<String, String> Map = new HashMap<>() {{
      put("test", "one two");
      put("foo", "bar");
}};
Pablo Fernandez
  • 103,170
  • 56
  • 192
  • 232
3

A way I've seen, when sticking to the base JDK, is to just use anonymous initializers:

Map<String, String> parameters = new HashMap<String, String>() {{
  put("test", "one two");
  put("foo", "bar");
}};

You can also take a look at the Guava ImmutableMap builder: http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ImmutableMap.Builder.html

If you want to get a little far out there you could write a parser for something like JSON (or just JSON itself and a JSON library) and then write the Map as a string.

aparker42
  • 986
  • 7
  • 3