Java's built-in toString() method converts Map back to String type
In Java,Map
The interface is correcttoString()
The method has been rewritten, so you can call this method directlyMap
Convert toString
type.
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. CreateMap
Example:useHashMap
The class creates aMap
ExamplescoreMap
, and some key-value pairs were added.
2. CalltoString()
method: DirectlyscoreMap
Called uptoString()
Method,Map
Convert toString
Type, the result is stored inmapAsString
in 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 quickMap
The 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.