Convert HashMap.toString() to HashMap in Java – 在 Java 中将 HashMap.toString() 转换为 HashMap

最后修改: 2023年 10月 14日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.导言

Java’s HashMap class is a widely used data structure that stores key-value pairs.

Java 的 HashMap 类是一种广泛使用的数据结构,用于存储键值对。

In this tutorial, we’ll delve into the process of converting a HashMap‘s string representation, obtained through the toString() method, back to a HashMap object in Java.

在本教程中,我们将深入探讨通过 toString() 方法将 HashMap 的字符串表示转换回 Java 中 HashMap 对象的过程。

2. Understanding HashMap String Representation

2.了解 HashMap 字符串表示法

Before we dive into the conversion process, let’s gain a solid understanding of HashMap and its String representation. Each key within a HashMap is uniquely linked to a corresponding value, offering efficient data retrieval based on these keys.

在深入了解转换过程之前,让我们扎实地了解一下 HashMap 及其 String 表示法。HashMap 中的每个键都唯一链接到相应的值,从而根据这些键提供高效的数据检索。

Moreover, the toString() method in HashMap provides a string representation of the map, encapsulating all its key-value pairs.

此外,HashMap中的toString()方法提供了映射的字符串表示,封装了所有键值对

In certain scenarios, we might encounter a HashMap‘s string representation from external sources, such as files or network requests. Hence, to effectively work with this data, it’s imperative to reconstitute the string representation into a usable HashMap object. This conversion process involves meticulous string parsing to extract the key-value pairs.

在某些应用场景中,我们可能会遇到来自外部资源(如文件或网络请求)的 HashMap 字符串表示。因此,要有效地处理这些数据,必须将字符串表示重组为可用的 HashMap 对象。这一转换过程涉及细致的字符串解析,以提取键值对。

3. The Conversion Process

3.转换过程

Let’s look at the steps required to convert a HashMap‘s string representation to a corresponding HashMap object:

让我们来看看将 HashMap 的字符串表示转换为相应的 HashMap 对象所需的步骤:

  • Obtain the String representation: Begin by acquiring the string representation of the HashMap, either from external sources or through manual creation.
  • Remove extraneous characters: The string representation obtained via toString() often includes extraneous characters like curly braces {} and spaces. Eliminate these characters to isolate the essential key-value pairs.
  • Split into key-value pairs: Subsequently, dissect the modified string into discrete key-value pair strings. These pairs are typically demarcated by commas.
  • Parsing key-value pairs: For each key-value pair string, dissect it into individual key and value components. These components can be separated by the equal sign (=) or another chosen delimiter.
  • Construct a new HashMap: For each extracted key-value pair, forge a new entry in a HashMap by associating the key with its corresponding value.
  • Error handling: Throughout the parsing process, exercise diligence in handling exceptions that may arise due to erroneous formatting or unexpected input.

4. Handling Simple Conversion

4.处理简单的转换

Let’s look at examples to solidify our understanding of the conversion process. In our example, we’ll demonstrate the conversion of a HashMap‘s string representation back into a HashMap object:

让我们通过示例来加深对转换过程的理解。在示例中,我们将演示将 HashMap 的字符串表示转换回 HashMap 对象:

String hashMapString = "{key1=value1, key2=value2, key3=value3}";
String keyValuePairs = hashMapString.replaceAll("[{}\\s]", "");
String[] pairs = keyValuePairs.split(",");

HashMap<String, String> actualHashMap = new HashMap<>();

for (String pair : pairs) {
    String[] keyValue = pair.split("=");
    if (keyValue.length == 2) {
        actualHashMap.put(keyValue[0], keyValue[1]);
    }
}

The code involves removing unnecessary characters from the input string, splitting it into key-value pairs, and populating a new HashMap accordingly.

代码包括删除输入字符串中不必要的字符,将其拆分为键值对,并相应地填充一个新的 HashMap

5. Handling Complex Conversion

5.处理复杂的转换

When a HashMap contains complex types as values, such as custom objects, the process of converting the string representation back to a HashMap object becomes more intricate. Custom logic is needed to deserialize these complex objects from their string representations during the parsing process.

HashMap 包含作为值的复杂类型(如自定义对象)时,将字符串表示转换回 HashMap 对象的过程将变得更加复杂。在解析过程中,需要自定义逻辑来从字符串表示反序列化这些复杂对象。

To illustrate this, let’s consider an example using a ConvertHashMapStringToHashMapObjectUsingtoString class. This class is equipped with a custom toString() method to facilitate serialization:

为了说明这一点,让我们考虑一个使用 ConvertHashMapStringToHashMapObjectUsingtoString 类的示例。该类配备了一个自定义的 toString() 方法,以方便序列化:

class ConvertHashMapStringToHashMapObjectUsingtoString {
    private String name;
    private int age;

    public ConvertHashMapStringToHashMapObjectUsingtoString (String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "{name=" + name + ", age=" + age + "}";
    }
}

Next, let’s create a deserializeCustomObject() method that can be used to deserialize the custom object from its string representation:

接下来,让我们创建一个 deserializeCustomObject() 方法,用于从字符串表示反序列化自定义对象:

private static ConvertHashMapStringToHashMapObjectUsingtoString deserializeCustomObject(String valueString) {
    if (valueString.startsWith("{") && valueString.endsWith("}")) {
        valueString = valueString.substring(1, valueString.length() - 1);
        String[] parts = valueString.split(",");
        String name = null;
        int age = -1;

        for (String part : parts) {
            String[] keyValue = part.split("=");
            if (keyValue.length == 2) {
                String key = keyValue[0].trim();
                String val = keyValue[1].trim();
                if (key.equals("name")) {
                    name = val;
                } else if (key.equals("age")) {
                    age = Integer.parseInt(val);
                }
            }
        }

        if (name != null && age >= 0) {
            return new ConvertHashMapStringToHashMapObjectUsingtoString(name, age);
        }
    }

    return new ConvertHashMapStringToHashMapObjectUsingtoString("", -1);
}

Now, let’s demonstrate how to use this logic to deserialize a HashMap with custom objects as values:

现在,让我们来演示如何使用此逻辑反序列化以自定义对象为值的 HashMap

public static void main(String[] args) {
    String hashMapString = "{key1={name=John, age=30}, key2={name=Alice, age=25}}";

    String keyValuePairs = hashMapString.replaceAll("[{}\\s]", "");

    String[] pairs = keyValuePairs.split(",");

    Map<String, ConvertHashMapStringToHashMapObjectUsingtoString> actualHashMap = new HashMap<>();

    for (String pair : pairs) {
        String[] keyValue = pair.split("=");
        if (keyValue.length == 2) {
            String key = keyValue[0];
            ConvertHashMapStringToHashMapObjectUsingtoString value = deserializeCustomObject(keyValue[1]);
            actualHashMap.put(key, value);
        }
    }

    System.out.println(actualHashMap);
}

5. Conclusion

5.结论

Converting a HashMap‘s string representation back to a HashMap in Java involves a systematic process of parsing and populating key-value pairs.

在 Java 中将 HashMap 的字符串表示转换回 HashMap 涉及到解析和填充键值对的系统过程。

By following the steps outlined in this article and utilizing the provided example, we can effectively convert HashMap strings into usable HashMap objects.

按照本文概述的步骤并利用所提供的示例,我们可以有效地将 HashMap 字符串转换为可用的 HashMap 对象。

This ability is particularly useful when dealing with data received from external sources or when serializing and deserializing HashMaps.

在处理从外部源接收的数据时,或在序列化和反序列化 HashMaps 时,该功能尤其有用。

As always, the complete code samples for this article can be found over on GitHub.

与往常一样,本文的完整代码示例可在 GitHub 上找到