SoFunction
Updated on 2025-05-19

Java uses the built-in toString method to convert Map back to String type

Java's built-in toString() method converts Map back to String type

In Java,MapThe interface is correcttoString()The method has been rewritten, so you can call this method directlyMapConvert toStringtype.

toString()The method will{key1=value1, key2=value2, ...}This format outputs strings.

The following is the detailed sample code

import ;
import ;

public class MapToStringUsingBuiltIn {
    public static void main(String[] args) {
        // Create a Map instance and add a key-value pair        Map<String, Integer> scoreMap = new HashMap<>();
        ("Alice", 85);
        ("Bob", 90);
        ("Charlie", 78);

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

        // Output the converted string        ("Map converted string form: " + mapAsString);
    }
}

Code explanation

1. CreateMapExample:useHashMapThe class creates aMapExamplescoreMap, and some key-value pairs were added.

2. CalltoString()method: DirectlyscoreMapCalled uptoString()Method,MapConvert toStringType, the result is stored inmapAsStringin variable.

3. Output result: Print out the converted string.

Run the above code and the output result is as follows:

Map converted string form: {Alice=85, Bob=90, Charlie=78}

This method is simple and convenient, suitable for quickMapThe content is displayed in string form.

But be carefultoString()The string format returned by the method is fixed. If you need a custom format, you have to manually splice the string.

Summarize

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