How to initialize a HashMap in Java using a literal approach?
Hello everyone! I just started learning Java and encountered a problem. In Python, I can declare a dictionary literally, for example:
```python
my_dict = {"key1": "value1", "key2": "value2"}
```
But in Java, when I try to do something similar for HashMap, it doesn't work. I have to write this cumbersome code:
```java
HashMap map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
```
This is very inconvenient, especially when you need to initialize a small map with known values. I've heard about some "double brace initialization", but I read that it's a bad practice. Is there a way in Java to declare a HashMap literally, like in Python? To immediately pass all key-value pairs at the moment of object creation.
No answers yet.
Log in to leave an answer