How to update value by key in HashMap? Detailed guide
Hello everyone! I'm new to Java and can't figure out HashMap. I have a simple task: I store user data in a HashMap where the key is the user ID (Integer) and the value is their name (String). I need to replace the user's name if it already exists, or add a new entry if there is no such ID.
Here is my code:
```java
HashMap users = new HashMap<>();
users.put(1, "Anna");
users.put(2, "Boris");
users.put(3, "Victor");
// Trying to update user with ID = 2
users.put(2, "Boris Updated");
```
I noticed that `put()` does replace the value if the key already exists. But I'm not sure if this is the correct approach. It seems to me that there should be a special method for updating, not the same `put()`.
Also I heard about the `repl
No answers yet.
Log in to leave an answer
Blogs
CI/CD for TypeScript Projects: GitHub Actions