How to Pretty-Print a Map in Java – 如何在 Java 中漂亮地打印地图

最后修改: 2024年 2月 25日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.导言

Pretty-printing a Map in Java involves formatting and displaying the key-value pairs of the map in a visually appealing and readable manner. While Java doesn’t provide a built-in method for pretty-printing maps, we have to implement a custom solution.

在 Java 中漂亮地打印 Map 涉及以视觉上吸引人和可读的方式格式化和显示地图的键值对。虽然 Java 没有提供漂亮打印地图的内置方法,但我们必须实现自定义解决方案。

In this tutorial, we’ll learn how to achieve this goal. Depending on our preferences and the level of detail, we’ll explore multiple approaches, using only standard JDK and then external libraries.

在本教程中,我们将学习如何实现这一目标。根据我们的偏好和详细程度,我们将探索多种方法,仅使用标准 JDK,然后使用外部库。

2. Creating a Map

2.创建地图</em

Before we move on, let’s create a map to work with:

在继续之前,我们先创建一张地图:

Map<String, Object> map = Map.of(
  "one", 1,
  "two", 2,
  "inner", Map.of(
    "ten", 10,
    "eleven", 11
  )
);

Notably, we’ve extended our example by adding an inner nested map.

值得注意的是,我们在示例中添加了一个内部嵌套地图。

3. Using Core Java

3.使用核心 Java

As we know, Java can print maps using a built-in toString() method:

我们知道,Java 可以使用内置的 toString() 方法打印地图:

{one=1, two=2, inner={eleven=11, ten=10}}

The output is preformatted in a simple way, displaying key-value pairs separated by commas on a single line. It works fine for simple maps or during debugging.

输出以简单的方式预先格式化,在一行中显示用逗号分隔的键值对。对于简单的地图或在调试过程中,它的效果很好。

But if we want a pretty-printed map, we have to implement custom methods.

但是,如果我们想要打印出漂亮的地图,就必须实现自定义方法。

3.1. Using a for-each Loop

3.1.使用 for-each 循环

When we need to iterate over all the elements, we can use a for-each loop:

当我们需要遍历所有元素时,可以使用 for-each 循环:

for (Map.Entry<?, ?> entry : map.entrySet()) {
     System.out.printf("%-15s : %s%n", entry.getKey(), entry.getValue());
}

This loop will print:

该循环将打印

one             : 1
two             : 2
inner           : {ten=10, eleven=11}

The output looks better now, but our inner map still isn’t pretty-printed, so we have to manually handle complex structures.

现在输出结果看起来更好了,但我们的内部地图仍然没有漂亮打印,因此我们必须手动处理复杂的结构。

To format our inner entries, let’s implement a helper function with a recursion and a left padding parametrized:

为了格式化我们的内部条目,让我们实现一个带有递归和左填充参数的辅助函数:

void printMap(int leftPadding, Map<?, ?> map) {
    for (Map.Entry<?, ?> entry : map.entrySet()) {
        if (entry.getValue() instanceof Map) {
            System.out.printf("%-15s :%n", entry.getKey());
            printMap(leftPadding + 4, (Map<?, ?>) entry.getValue());
        }
        else {
            System.out.printf("%" + (leftPadding > 0 ? leftPadding : "") + "s" // adding padding
              + "%-15s : %s%n",
              "", entry.getKey(), entry.getValue());
        }
    }
}

Now, if we execute the method by calling printMap(0, map), it’ll print:

现在,如果我们调用 printMap(0, map) 来执行该方法,它就会打印出来:

one             : 1
two             : 2
inner           :
    ten             : 10
    eleven          : 11

By implementing our custom solution, we’ll always have full control while printing our maps. We can customize our output by using built-in formatters such as the Formatter class, String.format(), or even System.out.printf(). On the other hand, a custom function might be a bit complicated if we’d like to handle multi-type or inner structures.

通过实施自定义解决方案,我们在打印地图时将始终拥有完全的控制权。我们可以通过使用内置格式器(如 Formatter 类String.format(),甚至 System.out.printf())来自定义输出。另一方面,如果我们想处理多类型或内部结构,自定义函数可能会有点复杂

3.2. Using Stream

3.2.使用 Stream

In Java, we can replace almost any for-each loop with a Stream. We can use one line to print and format our map:

在 Java 中,我们几乎可以用 Stream 代替任何 for-each 循环。我们可以用一行来打印和格式化我们的地图:

map.forEach((k, v) -> System.out.printf("%-15s : %s%n", k, v));

If we want more control, we can expand the stream and use map() or Collectors.joining() functions:

如果我们需要更多控制,可以扩展流并使用 map() Collectors.joining() 函数:

System.out.println(MAP.entrySet().stream()
  .map(entry -> String.format("%-15s : %s", entry.getKey(), entry.getValue()))
  .collect(Collectors.joining("\n")));

In both examples, we’ll get:

在这两个例子中,我们都会得到

one             : 1
two             : 2
inner           : {ten=10, eleven=11}

Once again, this approach gives us more control over formatting and works great for simple types. We must remember to manually handle any complex structures, as we did previously.

同样,这种方法为我们提供了更多的格式化控制,并且非常适合简单类型。我们必须记住,要像以前那样手动处理任何复杂结构

4. External Libraries

4.外部图书馆

Implementing a custom pretty-print feature might be a good choice if we don’t have a complex map. Any additional mappings will make our code more complicated and not worth implementing. Let’s check the solutions provided by external libraries.

如果我们没有复杂的映射,实施自定义 pretty-print 功能可能是一个不错的选择。任何额外的映射都会让我们的代码变得更加复杂,不值得实施。让我们看看外部库提供的解决方案。

4.1. Jackson

4.1.Jackson

If we compare JSON and map, we can find many similarities. In both cases, key-value pairs are used to represent entries.

如果我们比较一下 JSON 和 map,就会发现两者有很多相似之处。在这两种情况下,都使用键值对来表示条目。

First, let’s inspect Jackson, one of the most popular JSON libraries, by including its dependency in our pom.xml:

首先,让我们在 pom.xml 中加入最流行的 JSON 库之一Jackson的依赖关系,对其进行检查:

<dependency> 
    <groupId>com.fasterxml.jackson.core</groupId> 
    <artifactId>jackson-databind</artifactId> 
    <version>2.16.1</version>
</dependency>

Jackson provides an ObjectMapper class that can be used not only to work with JSON but also with standard maps:

Jackson 提供了ObjectMapper,该类不仅可用于处理 JSON,还可用于处理标准地图:

String json = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(map);

As a result, Jackson API pretty-prints our map:

因此,杰克逊应用程序接口会漂亮地打印我们的地图:

{
  "one" : 1,
  "two" : 2,
  "inner" : {
    "ten" : 10,
    "eleven" : 11
  }
}

This solution automatically handles our inner map, and it’s much simpler than previous ones. Unfortunately, we don’t have full control over the mapping.

这个解决方案自动处理我们的内部映射,比之前的解决方案要简单得多。遗憾的是,我们无法完全控制映射

4.2. Gson

4.2 Gson

Of course, other JSON libraries also support maps for pretty-printing. Let’s check out Gson by adding the latest version of its dependency:

当然,其他 JSON 库也支持用于漂亮打印的映射。让我们通过添加最新版本的依赖关系来查看Gson

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>

Just like we did previously, let’s configure a GsonBuilder:

就像我们之前所做的那样,让我们配置一个 GsonBuilder

String json = new GsonBuilder().setPrettyPrinting().create().toJson(MAP);

And here’s the result now:

这就是现在的结果:

{
  "one": 1,
  "two": 2,
  "inner": {
    "ten": 10,
    "eleven": 11
  }
}

Notably, we have slightly different formatting (no space after the key), but again, it’s much easier to pretty-print maps supporting nested values.

值得注意的是,我们的格式略有不同(键后没有空格),但同样,漂亮地打印支持嵌套值的映射要容易得多。

4.3. Apache Commons Collections

4.3.阿帕奇共享资源集

When we know that JSON libraries often support JSON and maps for pretty-printing, let’s explore other solutions provided by non-JSON libraries.

当我们知道JSON 库通常支持 JSON 和地图的漂亮打印时,让我们来探索一下非 JSON 库提供的其他解决方案。

Let’s check out Apache Commons Collections by adding a dependency to our project:

让我们通过在项目中添加依赖关系来查看 Apache Commons Collections

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>

The library brings us the MapUtils class. Let’s use it to print our map:

该库为我们带来了MapUtils。让我们用它来打印地图:

MapUtils.debugPrint(System.out, "map", map);

As a result, we’ll get the map formatted like this:

因此,我们将得到如下格式的地图:

map = 
{
    one = 1 java.lang.Integer
    two = 2 java.lang.Integer
    inner = 
    {
        ten = 10 java.lang.Integer
        eleven = 11 java.lang.Integer
    } java.util.HashMap
} java.util.HashMap

We’ve just used a debugPrint() method to format the map. If we want to omit the class name of our values, we can use a verbosePrint().

我们刚刚使用了 debugPrint() 方法来格式化地图。如果我们想省略值的类名,可以使用 verbosePrint() 方法。

4.4. Google Guava

4.4 谷歌石榴

Finally, let’s check out the approach provided by the Google Guava library. Before starting, let’s update our pom.xml:

最后,让我们来看看 Google Guava 库提供的方法。在开始之前,让我们更新一下 pom.xml

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>33.0.0-jre</version>
</dependency>

To print our map, we can use the Joiner class:

要打印地图,我们可以使用 Joiner

String mapStr = Joiner.on(",\n").withKeyValueSeparator("=").join(map);

If we now check the result, we’ll get:

如果现在检查结果,我们会得到

one=1,
two=2,
inner={ten=10, eleven=11}

Unfortunately, this approach can’t handle nested entries, but it works well for single-level structures.

遗憾的是,这种方法无法处理嵌套条目,但对于单层结构却很有效。

5. Conclusion

5.结论

In this article, we learned different approaches to pretty-print maps in Java. As we know, printing using the built-in toString() method can result in an unreadable, single-line string.

在本文中,我们学习了在 Java 中漂亮打印地图的不同方法。我们知道,使用内置的 toString() 方法打印可能会导致无法阅读的单行字符串。

We started by implementing the custom pretty-print methods using standard Java API, especially the for-each loops, streams, and formatters. This approach suits us if we have simple, non-nested maps or want full control over the mapping.

我们首先使用标准 Java API(尤其是 for-each 循环、流和格式化器)实现自定义的 pretty-print 方法如果我们有简单的非嵌套映射或希望完全控制映射,这种方法就适合我们。

After that, we inspected the solutions provided by external libraries like Jackson, Gson, Apache Commons Collections, or Guava. An external API is always simpler than implementing the custom solution, but we have less control over the predefined print format.

之后,我们检查了外部库(如 Jackson、Gson、Apache Commons Collections 或 Guava)提供的解决方案。外部 API 总是比实施自定义解决方案更简单,但我们对预定义打印格式的控制较少。

As always, the source code accompanying the article can be found over on GitHub.

一如既往,您可以在 GitHub 上找到本文的源代码