To initialize a HashMap
with values in Java, you can use the put()
method.
Here is an example of how to initialize a HashMap
with values in Java:
Map<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); map.put("cherry", 3);
In this example, the map
variable is initialized with a new HashMap
object, and the elements ("apple", 1), ("banana", 2), and ("cherry", 3) are added to the map using the put()
method.
You can also use the putAll()
method to initialize a HashMap
with the contents of another map:
Map<String, Integer> map1 = new HashMap<>(); map1.put("apple", 1); map1.put("banana", 2); Map<String, Integer> map2 = new HashMap<>(); map2.put("cherry", 3); map2.put("date", 4); map1.putAll(map2);
In this example, the map1
variable is initialized with the elements ("apple", 1) and ("banana", 2), and the map2
variable is initialized with the elements ("cherry", 3) and ("date", 4). The putAll()
method is then used to copy the elements of map2
into map1
, resulting in a map1
that contains the elements ("apple", 1), ("banana", 2), ("cherry", 3), and ("date", 4).
For more information on the Map
interface and the HashMap
class in Java, you can refer to the Java documentation.