Best Map Designer

Is there a more simplified 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 am looking for something closer to this.

  Map<String, String> map = MapBuilder.build("a", "apple", "b", "bear", "c", "cat"); 
+6
source share
4 answers

No, no, but I wrote a method to do just that, inspired by the Objective-C class of NSDictionary:

 public static Map<String, Object> mapWithKeysAndObjects(Object... objects) { if (objects.length % 2 != 0) { throw new IllegalArgumentException( "The array has to be of an even size - size is " + objects.length); } Map<String, Object> values = new HashMap<String, Object>(); for (int x = 0; x < objects.length; x+=2) { values.put((String) objects[x], objects[x + 1]); } return values; } 
+13
source

Always double-bound 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 the HashMap, not the HashMap. If you need to serialize a map, then be aware that serializing inner classes is not recommended .

+13
source

You can use ImmutableMap.Builder from the Google collection library.

+7
source

You can always use double binding:

 Map<String, String> map = new HashMap<String, String>() {{ put("foo", "bar"); put("baz", "qux"); }} 

But keep in mind that this may be ineffective according to these answers .

+3
source

Source: https://habr.com/ru/post/893618/


All Articles