Map to String Conversion in Java – Java中地图到字符串的转换

最后修改: 2019年 1月 16日

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

1. Overview

1.概述

In this tutorial, we’ll focus on conversion from a Map to a String and the other way around.

在本教程中,我们将重点讨论从MapString的转换,以及反过来的转换。

First, we’ll see how to achieve these using core Java methods, and afterward, we’ll use some third-party libraries.

首先,我们将看到如何使用核心Java方法来实现这些,之后,我们将使用一些第三方库。

2. Basic Map Example

2.基本地图实例

In all examples, we’re going to use the same Map implementation:

在所有的例子中,我们将使用同一个Map实现。

Map<Integer, String> wordsByKey = new HashMap<>();
wordsByKey.put(1, "one");
wordsByKey.put(2, "two");
wordsByKey.put(3, "three");
wordsByKey.put(4, "four");

3. Convert a Map to a String by Iterating

3.通过迭代将Map转换为String

Let’s iterate over all the keys in our Map and, for each of them, append the key-value combination to our resulting StringBuilder object.

让我们遍历我们的Map中的所有键,对于每一个键,将键值组合附加到我们的结果StringBuilder对象。

For formatting purposes, we can wrap the result in curly brackets:

出于格式化的目的,我们可以用大括号把结果包起来。

public String convertWithIteration(Map<Integer, ?> map) {
    StringBuilder mapAsString = new StringBuilder("{");
    for (Integer key : map.keySet()) {
        mapAsString.append(key + "=" + map.get(key) + ", ");
    }
    mapAsString.delete(mapAsString.length()-2, mapAsString.length()).append("}");
    return mapAsString.toString();
}

To check if we converted our Map correctly, let’s run the following test:

为了检查我们是否正确转换了我们的Map,让我们运行以下测试。

@Test
public void givenMap_WhenUsingIteration_ThenResultingStringIsCorrect() {
    String mapAsString = MapToString.convertWithIteration(wordsByKey);
    Assert.assertEquals("{1=one, 2=two, 3=three, 4=four}", mapAsString);
}

4. Convert a Map to a String Using Java Streams

4.使用Java Streams将Map转换为String

To perform conversion using streams, we first need to create a stream out of the available Map keys.

为了使用流进行转换,我们首先需要从可用的Map键中创建一个流。

Second, we’re mapping each key to a human-readable String.

第二,我们将每个键映射到一个人类可读的String

Finally, we’re joining those values, and, for the sake of convenience, we’re adding some formatting rules using the Collectors.joining() method:

最后,我们将这些值连接起来,为了方便起见,我们使用Collectors.join()方法添加一些格式化规则。

public String convertWithStream(Map<Integer, ?> map) {
    String mapAsString = map.keySet().stream()
      .map(key -> key + "=" + map.get(key))
      .collect(Collectors.joining(", ", "{", "}"));
    return mapAsString;
}

5. Convert a Map to a String Using Guava

5.使用Guava将Map转换为String

Let’s add Guava into our project and see how we can achieve the conversion in a single line of code:

让我们把Guava添加到我们的项目中,看看我们如何在一行代码中实现转换。

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

To perform the conversion using Guava’s Joiner class, we need to define a separator between different Map entries and a separator between keys and values:

为了使用Guava的Joiner类进行转换,我们需要在不同的Map条目之间定义一个分隔符,在键和值之间定义一个分隔符。

public String convertWithGuava(Map<Integer, ?> map) {
    return Joiner.on(",").withKeyValueSeparator("=").join(map);
}

6. Convert a Map to a String Using Apache Commons

6.使用Apache Commons将Map转换为String

To use Apache Commons, let’s add the following dependency first:

要使用Apache Commons,让我们首先添加以下依赖关系。

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

The joining is very straightforward — we just need to call the StringUtils.join method:

连接是非常直接的 – 我们只需要调用StringUtils.join方法。

public String convertWithApache(Map map) {
    return StringUtils.join(map);
}

One special mention goes to the debugPrint method available in Apache Commons. It is very useful for debugging purposes.

要特别提到的是Apache Commons中的debugPrint方法。它对调试工作非常有用。

When we call:

当我们打电话时。

MapUtils.debugPrint(System.out, "Map as String", wordsByKey);

the debug text will be written to the console:

调试文本将被写到控制台。

Map as String = 
{
    1 = one java.lang.String
    2 = two java.lang.String
    3 = three java.lang.String
    4 = four java.lang.String
} java.util.HashMap

7. Convert a String to a Map Using Streams

7.使用流将字符串转换为地图

To perform conversion from a String to a Map, let’s define where to split on and how to extract keys and values:

为了执行从StringMap的转换,让我们定义在哪里进行分割以及如何提取键和值。

public Map<String, String> convertWithStream(String mapAsString) {
    Map<String, String> map = Arrays.stream(mapAsString.split(","))
      .map(entry -> entry.split("="))
      .collect(Collectors.toMap(entry -> entry[0], entry -> entry[1]));
    return map;
}

8. Convert a String to a Map Using Guava

8.使用Guava将String转换为Map

A more compact version of the above is to rely on Guava to do the splitting and conversion for us in a one-line process:

上述的一个更紧凑的版本是依靠Guava在一个单行过程中为我们做分割和转换的工作。

public Map<String, String> convertWithGuava(String mapAsString) {
    return Splitter.on(',').withKeyValueSeparator('=').split(mapAsString);
}

9. Conclusion

9.结语

In this article, we saw how to convert a Map to a String and the other way around using both core Java methods and third-party libraries.

在这篇文章中,我们看到了如何使用核心Java方法和第三方库将Map转换为String,以及其他方式。

The implementation of all of these examples can be found over on GitHub.

所有这些例子的实现都可以在GitHub上找到over