Ben Noland
Ben Noland

Reputation: 34938

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");

Upvotes: 10

Views: 26772

Answers (5)

Aleksandr Dubinsky
Aleksandr Dubinsky

Reputation: 23505

Java 9 adds Map.of, such as:

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

Up to 10 entries are supported. For more entries you can use the overload taking Entry:

Map<String, String> map 
    = Map.ofEntries
        (Map.entry("a", "apple")
        , Map.entry("b", "bear")
        , Map.entry("c", "cat"));

Note that these methods do not return a HashMap. It returns an optimized immutable map.

Upvotes: 4

Nathan Hughes
Nathan Hughes

Reputation: 96395

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.

Upvotes: 17

Maur&#237;cio Linhares
Maur&#237;cio Linhares

Reputation: 40333

No, there isn't, but I wrote a method to do exactly this, inspired by Objective-C NSDictionary class:

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;

}

Upvotes: 13

whirlwin
whirlwin

Reputation: 16521

You could always use double brace initialization:

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

But bear in mind this might not be efficient according to these answers.

Upvotes: 2

Eugene Kuleshov
Eugene Kuleshov

Reputation: 31795

You could use ImmutableMap.Builder from Google collections library.

Upvotes: 9

Related Questions