Java
HashMap
Printing
Programming
Data Structures

Printing HashMap In Java

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Printing a HashMap in Java is easy for quick debugging, but the useful method depends on whether you care about speed, readability, stable ordering, or machine-parsable output. The key fact to remember is that HashMap does not guarantee iteration order, so the simplest output is not always the most informative one.

Quick Debug Output With toString

For local debugging, the default toString output is often enough.

java
1import java.util.HashMap;
2import java.util.Map;
3
4public class Main {
5    public static void main(String[] args) {
6        Map<String, Integer> scores = new HashMap<>();
7        scores.put("alice", 91);
8        scores.put("bob", 88);
9        scores.put("carol", 95);
10
11        System.out.println(scores);
12    }
13}

This is fast to write and useful for small maps. The drawback is that the order may vary, and the formatting becomes hard to read once the map grows.

If the output will be read by humans, iterating through the entries gives better control.

java
1import java.util.HashMap;
2import java.util.Map;
3
4public class Main {
5    public static void main(String[] args) {
6        Map<String, Integer> scores = new HashMap<>();
7        scores.put("alice", 91);
8        scores.put("bob", 88);
9        scores.put("carol", 95);
10
11        for (Map.Entry<String, Integer> entry : scores.entrySet()) {
12            System.out.printf("user=%s score=%d%n", entry.getKey(), entry.getValue());
13        }
14    }
15}

This is usually a better default for logs, because you can control labels, masking, and line structure.

Use Ordered Maps When Order Matters

A common mistake is expecting HashMap to print in a stable order. If deterministic output matters, sort it or use a different map type.

java
1import java.util.HashMap;
2import java.util.Map;
3import java.util.TreeMap;
4
5public class Main {
6    public static void main(String[] args) {
7        Map<String, Integer> raw = new HashMap<>();
8        raw.put("bob", 88);
9        raw.put("alice", 91);
10        raw.put("carol", 95);
11
12        Map<String, Integer> sorted = new TreeMap<>(raw);
13        sorted.forEach((k, v) -> System.out.println(k + " -> " + v));
14    }
15}

If insertion order is the requirement, use LinkedHashMap when the map is created rather than sorting it later.

Pretty-Print Nested Maps Carefully

For nested structures, a one-line dump gets hard to scan quickly. A small recursive printer can make hierarchical maps much clearer.

java
1import java.util.LinkedHashMap;
2import java.util.Map;
3
4public class PrettyMap {
5    static void printMap(Map<?, ?> map, int indent) {
6        String pad = " ".repeat(indent);
7        for (Map.Entry<?, ?> entry : map.entrySet()) {
8            Object value = entry.getValue();
9            if (value instanceof Map<?, ?> nested) {
10                System.out.println(pad + entry.getKey() + ":");
11                printMap(nested, indent + 2);
12            } else {
13                System.out.println(pad + entry.getKey() + ": " + value);
14            }
15        }
16    }
17
18    public static void main(String[] args) {
19        Map<String, Object> root = new LinkedHashMap<>();
20        Map<String, Object> db = new LinkedHashMap<>();
21        db.put("host", "localhost");
22        db.put("port", 5432);
23        root.put("service", "billing");
24        root.put("database", db);
25
26        printMap(root, 0);
27    }
28}

This is much easier to read during debugging than relying on a nested default toString output.

Use JSON for Machine-Readable Logging

If the output is meant for log ingestion or tooling rather than human inspection, serializing to JSON is often the better answer.

java
1import com.fasterxml.jackson.databind.ObjectMapper;
2import java.util.HashMap;
3import java.util.Map;
4
5public class JsonMapPrinter {
6    public static void main(String[] args) throws Exception {
7        Map<String, Object> payload = new HashMap<>();
8        payload.put("event", "score_update");
9        payload.put("user", "alice");
10        payload.put("score", 91);
11
12        ObjectMapper mapper = new ObjectMapper();
13        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(payload));
14    }
15}

That is usually more useful than ad hoc string formatting if another system will parse the output.

Common Pitfalls

The biggest pitfall is assuming HashMap order is stable. It is not. Another is dumping huge maps directly in hot code paths, where logging can become the dominant cost.

Developers also often print raw maps that contain secrets, tokens, or passwords. A readable formatter is still dangerous if it leaks the wrong data.

Finally, choose one output style based on purpose. A local debug dump, a human-readable log, and a machine-ingestible JSON event are different use cases and should not share the same assumptions.

Summary

  • 'System.out.println(map) is fine for quick local debugging.'
  • Iterate entries when you need readable and controlled output.
  • Use TreeMap or LinkedHashMap when order matters.
  • Pretty-print nested maps instead of relying on dense one-line dumps.
  • Use JSON serialization when the output is meant for tooling or structured logs.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.