Java - How to create new Entry (key, value)
To create a new key-value pair in a Map
in Java, you can use the put
method. For example:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 5);
map.put("banana", 3);
This creates a new HashMap and adds two key-value pairs to it: ("apple", 5) and ("banana", 3).
You can also use the putIfAbsent
method to add a new key-value pair to the map only if the key is not already present in the map. For example:
map.putIfAbsent("apple", 10); // does not add a new pair because "apple" is already a key in the map
map.putIfAbsent("orange", 10); // adds a new pair ("orange", 10)
You can also use the putAll
method to add all the key-value pairs from another map to the map:
Map<String, Integer> map2 = new HashMap<>();
map2.put("mango", 2);
map2.put("grape", 4);
map.putAll(map2); // adds all pairs from map2 to map