0

I need to create an empty map in java 8, then put some keys and values in it all at once. Is this possible? I have included code of what I want to do.

Map<String, String> data = new HashMap<String, String>();
data.put("candy" "chocolate", "shoes", "sneakers", "car", "prius");
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
personX
  • 39
  • 6

2 Answers2

0

In case of Java 8, you can do it like this.

new HashMap<String, String>() {
    {
        put("Key-1", "Value-1");
        put("Key-2", "Value-2");
    }
};

In case of Google Guava, you can do it like this.

ImmutableMap.of("Key-1", "Value-1", "Key-2", "Value-2");
Sambit
  • 7,625
  • 7
  • 34
  • 65
  • 2
    And, see [here](https://stackoverflow.com/a/27521360/5699679) for why you should not use so-called "double brace initialization". – Avi Aug 06 '19 at 17:14
  • 1
    Wow, I really appreciate your information. I really like it. – Sambit Aug 06 '19 at 17:16
  • that not a hashmap, that an anonymous innerclass subclass of hashmap, most likely no longer serializable. – user2023577 Aug 06 '19 at 18:31
  • Using your first example is a bad idea, as it creates an anonymous class that can hold a reference to an enclosing instance, it can lead to unintended and unexpected memory leaks. – Mark Rotteveel Aug 09 '19 at 19:06
  • Thank you Sir for pointing this concept, I got to know about it. – Sambit Aug 10 '19 at 05:47
0

As an alternative, if you do not have access to Java9+ and can use an outside library, you can use apache MapUtils putAll, docs found here:

public static Map putAll(Map map, Object[] array)

"Puts all the keys and values from the specified array into the map."

Example from docs:

 Map colorMap = MapUtils.putAll(new HashMap(), new String[] {
 "RED", "#FF0000",
 "GREEN", "#00FF00",
 "BLUE", "#0000FF"
 });
Nexevis
  • 4,647
  • 3
  • 13
  • 22