Junior
How to insert a value into a HashMap so as not to lose data?
sobes.tech AI
Answer from AI
Use the put method:
// Create a HashMap with String keys and Integer values
HashMap<String, Integer> myMap = new HashMap<>();
// Insert a value. If the key already exists, the old value will be replaced.
myMap.put("key1", 10);
// Insert another value.
myMap.put("key2", 20);
// Insert a value with an existing key.
// The old value ("key1" -> 10) will be replaced with the new one ("key1" -> 30).
myMap.put("key1", 30);
To prevent data loss when inserting with an existing key, you can use the putIfAbsent method:
// Create a HashMap
HashMap<String, Integer> myMap = new HashMap<>();
// Insert a value. The key "key1" does not exist, so the value will be added.
myMap.putIfAbsent("key1", 10); // myMap: {key1=10}
// Attempt to insert a value with an existing key.
// The key "key1" already exists, so the value 20 will not be added,
// and the old value (10) will remain.
myMap.putIfAbsent("key1", 20); // myMap: {key1=10}
// Insert a value with a new key.
myMap.putIfAbsent("key2", 30); // myMap: {key1=10, key2=30}