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.
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(...))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With