Convert a Map to a String in Java
This post will discuss how to convert a Map to a String in Java.
1. Using toString() method
A simple approach is to get the string representation of the map using the toString() method. The string representation of a map consists of a list of key-value pairs enclosed within curly braces, where the adjacent pairs are delimited by a comma followed by a single space and each key-value pair is separated by the equals sign (=). i.e., {K1=V1, K2=V2, ..., Kn=Vn}.
Following is a simple example demonstrating the string representation of the map:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { Map<String, Integer> lang = new HashMap<>(); lang.put("C++", 1980); lang.put("Java", 1995); lang.put("Ruby", 1991); String str = lang.toString(); System.out.println(str); } } |
Output:
{Java=1995, C++=1980, Ruby=1991}
2. Using Guava
Guava’s Joiner class is designed to customize the string representation of an object. Just create a joiner, and configure the separator, and specify the collection to be added.
The following code demonstrates it:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import com.google.common.base.Joiner; import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { Map<String, Integer> lang = new HashMap<>(); lang.put("C++", 1980); lang.put("Java", 1995); lang.put("Ruby", 1991); String str = Joiner.on("|").withKeyValueSeparator(":").join(lang); System.out.println(str); } } |
Output:
Java:1995|C++:1980|Ruby:1991
3. Using Stream API
With Java 8 and above, you can get the string representation of a map using a Stream API, easily customized according to your needs.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { Map<String, Integer> lang = new HashMap<>(); lang.put("C++", 1980); lang.put("Java", 1995); lang.put("Ruby", 1991); String str = lang.entrySet().stream().map(e -> e.getKey() + ":" + e.getValue()) .collect(Collectors.joining("|")); System.out.println(str); } } |
Output:
Java:1995|C++:1980|Ruby:1991
That’s all about converting a Map to a String in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)