Java collection framework map

Map in the Java collection framework is a collection type used to store key-value pairs. Each key-value pair contains a key object and a value object, and there is a mapping relationship between them, that is, the corresponding value object can be obtained through the key object. A key object can be used to access and manipulate the corresponding value object.

Common Map implementation classes in Java include HashMap, TreeMap, and LinkedHashMap. Among them, HashMap is the most commonly used implementation class, which is implemented based on the hash table data structure and has the characteristics of fast search. TreeMap is implemented based on the red-black tree data structure, which provides an ordered key-value pair access method. LinkedHashMap adds a linked list on the basis of HashMap to ensure the order of key-value pairs.

Common methods in the Map interface include: put (Object key, Object value), get (Object key), remove (Object key), etc. The above methods can implement functions such as adding elements to the Map, obtaining the value of the specified key, and deleting the key-value pair corresponding to the specified key.

Here is a simple Map example:

java

import java.util.HashMap; import java.util.Map; public class MapExample { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); // 向Map中添加元素 map.put("apple", 1); map.put("banana", 2); map.put("orange", 3); // 获取指定键的值 int value = map.get("banana"); System.out.println("The value of 'banana' is: " + value); // 删除指定键所对应的键值对 map.remove("orange"); // 遍历Map中的元素 for (Map.Entry<String, Integer> entry : map.entrySet()) { String key = entry.getKey(); int val = entry.getValue(); System.out.println("Key: " + key + ", Value: " + val); } } }

The output is:

The value of 'banana' is: 2 Key: apple, Value: 1 Key: banana, Value: 2

Common Map implementation classes in Java include HashMap, TreeMap, and LinkedHashMap. Among them, HashMap is the most commonly used implementation class, which is implemented based on the hash table data structure and has the characteristics of fast search. TreeMap is implemented based on the red-black tree data structure, which provides an ordered key-value pair access method. LinkedHashMap adds a linked list on the basis of HashMap to ensure the order of key-value pairs.

Guess you like

Origin blog.csdn.net/m0_67906358/article/details/130095472