📅  最后修改于: 2023-12-03 14:42:15.206000             🧑  作者: Mango
In Java, a Map is an interface that maps keys to values. It is commonly used to store or retrieve data in a key-value pair format. In this article, we will explore how to create a Java Map with values.
To create a Java Map with values, we can use the java.util.Map
interface. This interface has several implementations, such as HashMap
, TreeMap
, and LinkedHashMap
. Each implementation has different characteristics, but the basic concept of mapping keys to values remains the same.
Here is an example of how to create a HashMap
with values:
Map<String, Integer> myMap = new HashMap<>();
myMap.put("One", 1);
myMap.put("Two", 2);
myMap.put("Three", 3);
In the example above, we created a HashMap
with String
keys and Integer
values. We then added three key-value pairs to the map using the put
method.
To retrieve values from a Java Map, we can use the get
method. This method takes a key as a parameter and returns the corresponding value.
Here is an example of how to retrieve values from the HashMap
we created earlier:
System.out.println(myMap.get("One")); // Output: 1
System.out.println(myMap.get("Two")); // Output: 2
System.out.println(myMap.get("Three")); // Output: 3
In the example above, we used the get
method to retrieve the values associated with the keys "One", "Two", and "Three".
In this article, we learned how to create a Java Map with values using the java.util.Map
interface. We also learned how to retrieve values from a Java Map using the get
method. This basic concept of mapping keys to values is essential in many Java applications, and we hope this article helps you get started with using Maps in your own projects.