Create and populate TreeMap in one line

Tags: ,



Like an array new Integer[]{ 1, 2, 3 }, can I create and populate a TreeMap using just one line?

// I want to use it in situations like this:
this.lookFor( new TreeMap( {...} ) );

Any chances for HashMap or LinkedHashMap too?

Answer

There is no built-in syntax for specifically initializing maps. However, you can take advantage of a special syntax known as “double brace initialization”.

Map<String, Integer> map = new TreeMap<String, Integer>() {{ put("one", 1); put("two", 2); put("three", 3); }};

The outer pair of braces means that you are declaring and initializing an anonymous inner class that extends TreeMap. The inner pair of braces represents an instance initializer, code that is run when an instance is created.



Source: stackoverflow