1

Is there a short and handy way to create pre-populated java map?

E.g. a new list can be easily created from an array using Arrays.asList("A", "B", "C") but there is no such method like Arrays.toMap({"key1", "value1"}, {"key2", "value2"}, ...) or

If there is no such method in JDK, is there a utility lib which I can use?

Thank you!

  • 2
    Since Java 9 you can create immutable map via static factory methods in Map interfaces like `Map.of(k1,v1,k2,v2,...)` or `Map.ofEntries(Map.entry(k1,v1),Map.entry(k2,v2),..)`. If you need mutable map you can use copy-constructor of your selected map like `new HashMal<>(Map.of(...))`. – Pshemo May 30 '19 at 17:58
  • 1
    @Pshemo thanks for your answer, that's what I needed. This questions should be updated with your suggestion https://stackoverflow.com/questions/7345241/builder-for-hashmap – user10867319 May 30 '19 at 17:59

1 Answers1

1

You can use Map<String, String> map = Map.of(key1, value1, key2, value2) for the most easy to use way.

(Map<String, String> is just an example. You can use the types you want)

Note that this creates immutable maps.

For mutable maps you can pass this map to a HashMap

Map<String, String> map = new HashMap<String, String>(
    Map.of(...)
);