When I print a Map using System.out.println(map), Java provides a nice string representation in the console. How can I achieve the same result but store it in a variable instead?
Is there a built-in method like Collections.toString(map), or what’s the best way to convert a Java Map to a String without using standard output?
Using toString() (Built-in Method)
The simplest way is to use the toString() method, which Java provides for Map objects:
Map<String, Integer> map = new HashMap<>();
map.put("Alice", 25);
map.put("Bob", 30);
String mapAsString = map.toString();
System.out.println(mapAsString);
Output:
{Alice=25, Bob=30}
Pros: Simple, built-in, works for most cases.
Cons: Not customizable (e.g., formatting, separators).
Using Java Streams (Custom Formatting)
If you want a custom string format, use Stream:
String formatted = map.entrySet().stream()
.map(e -> e.getKey() + "=" + e.getValue())
.collect(Collectors.joining(", ", "{", "}"));
System.out.println(formatted);
Output:
{Alice=25, Bob=30}
Pros: Fully customizable formatting.
Cons: Slightly more complex than toString().
Using JSON (For Readability & Data Transfer)
If you need structured output, use a JSON library like Jackson:
java
Copy
Edit
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(map);
System.out.println(json);
Output (JSON format):
{"Alice":25,"Bob":30}
Pros: Readable, structured, useful for APIs.
Cons: Requires an external library.