In Java,Map
Convert backString
Type, 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
Map
The interface itself is implementedtoString()
Method, it will follow{key1=value1, key2=value2, ...}
The format willMap
Convert 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
- Create a
HashMap
Examplemap
, and two key-value pairs were added. - Call
()
Method willMap
Convert to a string. - Print the converted string.
Method 2: Manually splice strings
If you need to customize the format of the string, you can manually traverse itMap
And 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 aHashMap
Examplemap
, and two key-value pairs were added.
2. UseStringBuilder
To splice strings, because it performs better when splicing strings frequently.
3. TraversalMap
ofentrySet()
, add each key-value pair toStringBuilder
and add commas and spaces between key-value pairs.
4. Add curly braces at the end andStringBuilder
Convert 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.