Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA Initialize a HashMap while declaring it [duplicate]

Tags:

java

hashmap

I am currently working with a prefilled Hashmap, but I cannot come up with an efficient way to declare a Hashmap instantly. One way I can do it is:

static final LinkedHashMap<String, Integer> test = new LinkedHashMap<String, Integer>() {{

}}

But I was told that this way is not good because of runtime etc.. I need a way though, to fill the List instantly and not in a method, because the method where I need it is accessed multiple times.

like image 832
Mal Avatar asked Nov 26 '25 12:11

Mal


1 Answers

Use java.util.Map#of() from Java 9+

static final Map<String, Integer> map = Map.of(
    "key1", 42,
    "key2", 69
);

If you specifically want a HashMap, use just that as a wrapper: new HashMap(Map.of(...))

like image 156
neu242 Avatar answered Nov 29 '25 01:11

neu242



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!