Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better Map Constructor

Is there a more streamlined way to do the following?

Map<String, String> map = new HashMap<String, String>();
map.put("a", "apple");
map.put("b", "bear");
map.put("c", "cat");

I'm looking for something closer to this.

 Map<String, String> map = MapBuilder.build("a", "apple", "b", "bear", "c", "cat");
like image 877
Ben Noland Avatar asked Jul 26 '11 17:07

Ben Noland


1 Answers

There's always double-brace initialization:

Map<String, String> map = new HashMap<String, String>(){{
    put("a", "apple"); put("b", "bear"); put("c", "cat");}};

There are problems with this approach. It returns an anonymous inner class extending HashMap, not a HashMap. If you need to serialize the map then know that serialization of inner classes is discouraged.

like image 166
Nathan Hughes Avatar answered Oct 14 '22 22:10

Nathan Hughes