0

Is there a way in java to specify the elements in a Map when calling the Map's constructor?

As an example of what I mean, let's say I want a map of the following key/value pairs:

foo: bar
baz: bat

I can add them to an existing Map like this:

Map<String, String> myMap = new HashMap<String, String>();
myMap.put("foo", "bar");
myMap.put("baz", "bat");

Is there a way to do something like this (with object literals borrowed from javascript as a substitute for what I want):

Map<String, String> myMap = new HashMap<String, String>({"foo": "bar", "baz": "bat"});

The reason I ask (in case it makes a difference), is that I want to pass a bunch of HashMaps in-line to a function call, and it would be quite convenient if I didn't have to create variables to hold them and add elements to each one, one at a time. I'm considering using a JSON parser and writing my Maps as javascript objects to save time, but it would a bit silly if that was really the optimal way to do this.

asgallant
  • 26,060
  • 6
  • 72
  • 87

2 Answers2

0

Alternatively, it can still be achieved via a custom class possible extending HashMap.

Create a class with an appropriate validation (I have considered even number of entries to form a key, value set):

public class MyMap extends HashMap<String, String> {

    public MyMap(String[] args) throws Exception {

        if ((args.length % 2) != 0) {
            throw new Exception("Key value pairs are not of required length");
        }

        for (int i = 1; i < args.length; i += 2) {
            this.put(args[i - 1], args[i]);

        }
    }
}

It traverses through the String array passed to the constructor and puts its values.

In the main calling class, we simply invoke the constructor with a String array:

public static void main(String... args) {
        try {
            MyMap myMap = new MyMap(
                    new String[] { "foo", "bar", "bat", "booze" });
            System.out.println(myMap.get("bat"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Output:

booze

StoopidDonut
  • 8,547
  • 2
  • 33
  • 51
0

you can use static block to populate a map

private Map<String, String> map;

static {
    map.put("key0", "value0");
    map.put("key1", "value1");
}
Dennis Meng
  • 5,109
  • 14
  • 33
  • 36
JosefN
  • 952
  • 6
  • 8