將 HashMap.toString() 轉換為 Java 中的 HashMap
一、簡介
Java的HashMap
類別是廣泛使用的儲存鍵值對的資料結構。
在本教程中,我們將深入研究將透過toString()
方法獲得的HashMap
字串表示形式轉換回 Java 中的HashMap
物件的過程。
2. 理解HashMap String
表示
在深入了解轉換過程之前,讓我們對HashMap
及其String
表示形式有一個深入的了解。 HashMap
中的每個鍵都唯一連結到對應的值,從而提供基於這些鍵的高效資料檢索。
此外, HashMap
中的toString()
方法提供了映射的字串表示形式,封裝了其所有鍵值對。
在某些情況下,我們可能會遇到來自外部來源(例如檔案或網路請求)的HashMap
字串表示形式。因此,為了有效地處理這些數據,必須將字串表示形式重新建構為可用的HashMap
物件。此轉換過程涉及細緻的字串解析以提取鍵值對。
3. 轉換過程
讓我們來看看將HashMap
的字串表示形式轉換為對應的HashMap
物件所需的步驟:
- 取得
String
表示形式:首先從外部來源或透過手動建立取得HashMap
的字串表示形式。 - 刪除無關字元:透過
toString()
取得的字串表示形式通常包含無關字符,例如大括號{}
和空格。消除這些字元以隔離必要的鍵值對。 - 拆分為鍵值對:隨後,將修改後的字串分解為離散的鍵值對字串。這些對通常用逗號分隔。
- 解析鍵值對:對於每個鍵值對字串,將其分解為單獨的鍵和值組件。這些元件可以用等號
(=)
或其他選取的分隔符號分隔。 - 建構一個新的
HashMap
:對於每個提取的鍵值對,透過將鍵與其對應的值關聯起來在HashMap
中偽造一個新條目。 - 錯誤處理:在整個解析過程中,請注意處理因格式錯誤或意外輸入而可能出現的異常。
4. 處理簡單轉換
讓我們來看一些例子來鞏固我們對轉換過程的理解。在我們的範例中,我們將示範將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]);
}
}
該代碼涉及從輸入字串中刪除不必要的字符,將其拆分為鍵值對,並相應地填充新的HashMap
。
5. 處理複雜的轉換
當HashMap
包含複雜類型作為值(例如自訂物件)時,將字串表示形式轉換回HashMap
物件的過程會變得更加複雜。在解析過程中,需要自訂邏輯來將這些複雜物件從其字串表示形式反序列化。
為了說明這一點,讓我們考慮一個使用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 + "}";
}
}
接下來,我們建立一個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);
}
現在,讓我們示範如何使用此邏輯以自訂物件作為值來反序列化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. 結論
將HashMap
的字串表示形式轉換回 Java 中的HashMap
涉及解析和填入鍵值對的系統過程。
透過遵循本文概述的步驟並利用提供的範例,我們可以有效地將HashMap
字串轉換為可用的HashMap
物件。
當處理從外部來源接收的資料或序列化和反序列化HashMaps
時,此功能特別有用。
與往常一樣,本文的完整程式碼範例可以在 GitHub 上找到。