Map is an interface that represents a collection of key-value pairs in Java and is used to store and search data efficiently. Its main uses include: storing data where each key corresponds to a unique value. Create unordered (HashMap), ordered (TreeMap), ordered and retain insertion order (LinkedHashMap) Maps. Add key-value pairs through the put() method, and obtain values through the get() method. Traverse the Map using key sets (keySet()) and value sets (values()). Use the remove() method to delete key-value pairs.
Usage of Map in Java
What is Map?
Map is an interface in Java, which represents a collection of key-value pairs. The key is used to uniquely identify each value, while the value can be any object.
Purpose:
Map is mainly used to store data, where each key corresponds to a unique value. This makes finding data, updating data, and deleting data very efficient.
Create Map:
You can use the following methods to create a Map:
HashMap
: unordered and duplicates allowed key. TreeMap
: Ordered and does not allow duplicate keys. LinkedHashMap
: Ordered and allows duplicate keys, but preserves the order in which elements were inserted. Add key-value pairs:
To add key-value pairs to the Map, you can use the put(key, value)
method . If the key already exists, the existing value will be overwritten.
Get the value:
The value associated with a given key can be obtained using the get(key)
method. If the key does not exist, returns null
.
Traverse the Map:
You can use the keySet()
and values()
methods to traverse the keys and values in the Map .
Delete key-value pairs:
You can use the remove()
method to delete key-value pairs associated with a given key.
Example:
The following is a sample code that uses HashMap to create and use Map:
<code class="java">Map<String, Integer> ages = new HashMap<>(); ages.put("John", 30); ages.put("Mary", 25); System.out.println(ages.get("John")); // 输出:30 for (String key : ages.keySet()) { System.out.println(key + ": " + ages.get(key)); }</code>
The above is the detailed content of How to use map in java. For more information, please follow other related articles on the PHP Chinese website!