[Java Basics] In-depth understanding of key-value pair collections in Java: Detailed explanation of Map collections

Insert image description here

Map is one of the commonly used data structures in Java, used to store key-value pair (Key-Value) mapping. It provides fast search and access capabilities and is one of the commonly used tools in programming. This article will provide an in-depth introduction to Map collections in Java, including common Map implementation classes, basic operations, usage examples, and some important considerations.

Basic concepts of Map

Before we begin, let's understand some basic Map concepts:

  • Key : Each key must be unique and used to find and access values.
  • Value : The data associated with the key.
  • Key-value pair (Entry) : Represents a combination of key and value.
  • Mapping : The relationship between keys and values.

Common Map implementation classes

Java provides a variety of Map implementation classes, each with different characteristics and uses. The following are some common Map implementation classes:

  1. HashMap : A hash table-based implementation that provides fast insertion and lookup performance. But the order of the elements is not guaranteed.

  2. TreeMap : Based on the implementation of red-black trees, elements are sorted by the natural order of keys or a custom order.

  3. LinkedHashMap : Based on the implementation of hash table and doubly linked list, the insertion order of elements is maintained.

  4. HashTable : Early hash table implementation, thread-safe, deprecated.

  5. ConcurrentHashMap : Thread-safe hash table implementation, suitable for multi-threaded environments.

Basic operations

1. Create a Map object

To create a Map object, use the constructor of its implementation class. For example, create a HashMap:

Map<String, Integer> hashMap = new HashMap<>();

2. Add key-value pairs

putYou can add key-value pairs to the Map using :

hashMap.put("apple", 1);
hashMap.put("banana", 2);

3. Get the value

Get the corresponding value by key:

int value = hashMap.get("apple"); // 返回1

4. Remove key-value pairs

Use removethis method to remove key-value pairs from a Map:

hashMap.remove("apple");

5. Determine whether the key exists

You can use containsKeythe method to determine if a key exists:

boolean contains = hashMap.containsKey("apple"); // 返回false

6. Get all keys or values

Use keySetmethod to get all keys, and use valuesmethod to get all values:

Set<String> keys = hashMap.keySet();
Collection<Integer> values = hashMap.values();

7. Traverse the Map

You can use an iterator or an enhanced for loop to iterate over the key-value pairs in the Map:

for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
    
    
    String key = entry.getKey();
    int value = entry.getValue();
    System.out.println(key + ": " + value);
}

Usage example

The following is a simple example that demonstrates how to use Map to count the number of occurrences of a word in a piece of text:

public static void main(String[] args) {
    
    
    String text = "This is a sample text. This text contains sample words.";

    // 创建一个Map来存储单词和出现次数
    Map<String, Integer> wordCountMap = new HashMap<>();

    // 使用正则表达式分割文本并统计单词
    String[] words = text.split("\\s+");
    for (String word : words) {
    
    
        // 删除标点符号
        word = word.replaceAll("[^a-zA-Z]", "").toLowerCase();

        // 更新单词的出现次数
        wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
    }

    // 打印单词和出现次数
    for (Map.Entry<String, Integer> entry : wordCountMap.entrySet()) {
    
    
        System.out.println(entry.getKey() + ": " + entry.getValue());
    }
}

This example splits text into words, counts the number of occurrences of each word, and stores the results in a Map.

More ways to use Map collections

When it comes to using Map collections in Java, there are also some advanced usages and methods that can help you manipulate data more flexibly and efficiently. Next, we will introduce some more ways to use Map collections:

1. putIfAbsentHow to use

putIfAbsentMethod can be used to check if the same key already exists when adding an element to the Map. If the key does not exist, it will add the key-value pair; if the key already exists, it will leave the original value unchanged.

Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);

map.putIfAbsent("apple", 2); // 不会生效,键"apple"已存在
map.putIfAbsent("banana", 3); // 添加键值对"banana"->3

2. Usage computeand computeIfAbsentmethods

computeMethod can be used to calculate a new value based on an existing key-value pair. It accepts a key and a BiFunctionfunction as parameters. computeIfAbsentThe method calculates a new value only when the key does not exist. It accepts a key and a Functionfunction.

Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);

map.compute("apple", (k, v) -> v + 1); // 更新键"apple"的值为2
map.compute("banana", (k, v) -> v + 1); // 不会生效,键"banana"不存在

map.computeIfAbsent("banana", k -> 1); // 添加键值对"banana"->1

3. mergeHow to use

mergeMethod can be used to merge existing key-value pairs, it accepts a key, a new value and a BiFunctionfunction as parameters. If the key does not exist, it will add the new key-value pair; if the key already exists, it will BiFunctionmerge the values ​​based on the logic of the function.

Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);

map.merge("apple", 2, (oldValue, newValue) -> oldValue + newValue); // 更新键"apple"的值为3
map.merge("banana", 1, (oldValue, newValue) -> oldValue + newValue); // 添加键值对"banana"->1

4. forEachHow to use

forEachThe method can be used to traverse the key-value pairs in the Map and can accept a BiConsumerfunction to process each key-value pair.

Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("cherry", 3);

map.forEach((key, value) -> System.out.println(key + ": " + value));

5. computeIfPresentHow to use

computeIfPresentThe method can calculate a new value only when the key exists. It accepts a key and a BiFunctionfunction as parameters.

Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);

map.computeIfPresent("apple", (key, value) -> value + 1); // 更新键"apple"的值为2
map.computeIfPresent("banana", (key, value) -> value + 1); // 不会生效,键"banana"不存在

6. replaceAllHow to use

replaceAllThe method can be used to replace all values ​​in the Map. It accepts a BiFunctionfunction as a parameter and is used to calculate the new value.

Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);

map.replaceAll((key, value) -> value * 2); // 将所有值乘以2

7. Use mergemethods to set default values

If you want to set a default value for a key in the Map, you can use mergethe method:

Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);

map.merge("banana", 10, Integer::sum); // 如果键"banana"不存在,将其值设置为10,如果存在,则使用sum函数合并值

These advanced usages can help you process data in the Map collection more flexibly, and choose the appropriate method to operate key-value pairs according to your needs. Remember, when using Map, it is very important to choose the appropriate method according to the specific scenario, which can improve the readability and performance of the code.

Considerations and best practices

There are some considerations and best practices to remember when using Maps:

1. Uniqueness of key

Keys in the Map must be unique. If you try to add a new value with the same key, the old value will be overwritten.

2. Use appropriate Map implementation classes

It is important to choose a Map implementation class that suits your needs. If you need fast search operations, you can choose HashMap; if you need ordered key-value pairs, you can choose TreeMap; if you need thread safety, you can choose ConcurrentHashMap.

3. Consider key and value types

Maps can use different types of keys and

value. Make sure that the key and value types meet your needs and do not throw type conversion errors.

4. Use EntrySet when traversing Map

When traversing a Map, use entrySetmethods to get a collection of key-value pairs instead of first getting a collection of keys and then getting the values ​​one by one. This improves performance.

5. Consider performance and memory consumption

When processing large amounts of data, be aware of Map performance and memory consumption. Choose appropriate data structures and algorithms to ensure performance.

Conclusion

This article introduces the Map collection in Java in detail, including common Map implementation classes, basic operations, usage examples, precautions and best practices. Map is a very useful data structure in Java programming, and mastering its use is very important for developing efficient applications. I hope this article can help you better understand and utilize Map collections in Java.

Guess you like

Origin blog.csdn.net/qq_21484461/article/details/132892515