SoFunction
Updated on 2025-05-19

How to convert Map back to String type

In Java,MapConvert backStringType, you can manually splice strings, or use Java built-intoString()method.

The following is a detailed introduction to these two methods.

Method 1: Use the toString() method

MapThe interface itself is implementedtoString()Method, it will follow{key1=value1, key2=value2, ...}The format willMapConvert to a string.

This method is simple and straightforward and works in most cases.

Here is the sample code:

import ;
import ;

public class MapToStringExample {
    public static void main(String[] args) {
        // Create a Map and add a key-value pair        Map<Integer, Integer> map = new HashMap<>();
        (1, 491);
        (2, 500);

        // Use the toString() method to convert Map to String        String mapAsString = ();

        // Output result        ("Converted string: " + mapAsString);
    }
}

Code explanation

  1. Create aHashMapExamplemap, and two key-value pairs were added.
  2. Call()Method willMapConvert to a string.
  3. Print the converted string.

Method 2: Manually splice strings

If you need to customize the format of the string, you can manually traverse itMapAnd splice the string.

Here is the sample code:

import ;
import ;

public class ManualMapToStringExample {
    public static void main(String[] args) {
        // Create a Map and add a key-value pair        Map<Integer, Integer> map = new HashMap<>();
        (1, 491);
        (2, 500);

        // Manually splice strings        StringBuilder sb = new StringBuilder();
        ("{");
        boolean first = true;
        for (<Integer, Integer> entry : ()) {
            if (!first) {
                (", ");
            }
            (()).append("=").append(());
            first = false;
        }
        ("}");
        String mapAsString = ();

        // Output result        ("Converted string: " + mapAsString);
    }
}

Code explanation

1. Create aHashMapExamplemap, and two key-value pairs were added.

2. UseStringBuilderTo splice strings, because it performs better when splicing strings frequently.

3. TraversalMapofentrySet(), add each key-value pair toStringBuilderand add commas and spaces between key-value pairs.

4. Add curly braces at the end andStringBuilderConvert to a string.

5. Print the converted string.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.