Convert a Map to an Array, List or Set in Java – 在Java中把地图转换成数组、列表或集合

最后修改: 2014年 6月 2日

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

1. Overview

1.概述

This short article will show how to convert the values of a Map to an Array, a List or a Set using plain Java as well as a quick Guava based example.

这篇短文将展示如何使用普通的Java以及快速的Guava实例将Map的值转换为Array、ListSet

This article is part of the “Java – Back to Basic” series here on Baeldung.

本文是Baeldung网站上“Java – Back to Basic “系列的一部分。

2. Map Values to Array

2.将数值映射到数组

First, let’s look at converting the values of the Map into an array, using plain java:

首先,让我们看看如何将Map的值转换为数组,使用普通java

@Test
public void givenUsingCoreJava_whenMapValuesConvertedToArray_thenCorrect() {
    Map<Integer, String> sourceMap = createMap();

    Collection<String> values = sourceMap.values();
    String[] targetArray = values.toArray(new String[0]);
}

Note, that toArray(new T[0]) is the preferred way to use the method over the toArray(new T[size]). As Aleksey Shipilëv proves in his blog post, it seems faster, safer, and cleaner.

注意,toArray(new T[0])是比toArray(new T[size])更好的使用方法。正如Aleksey Shipilëv在他的博客文章中所证明的那样,它似乎更快、更安全、更干净。

3. Map Values to List

3.将数值映射到列表

Next, let’s convert the values of a Map to a List – using plain Java:

接下来,让我们把Map的值转换为List–使用普通的Java。

@Test
public void givenUsingCoreJava_whenMapValuesConvertedToList_thenCorrect() {
    Map<Integer, String> sourceMap = createMap();

    List<String> targetList = new ArrayList<>(sourceMap.values());
}

And using Guava:

并使用番石榴。

@Test
public void givenUsingGuava_whenMapValuesConvertedToList_thenCorrect() {
    Map<Integer, String> sourceMap = createMap();

    List<String> targetList = Lists.newArrayList(sourceMap.values());
}

4. Map Values to Set

4.要设置的地图值

Finally, let’s convert the values of the Map to a Set, using plain java:

最后,让我们用普通的java将Map的值转换为Set。

@Test
public void givenUsingCoreJava_whenMapValuesConvertedToS_thenCorrect() {
    Map<Integer, String> sourceMap = createMap();

    Set<String> targetSet = new HashSet<>(sourceMap.values());
}

5. Conclusion

5.结论

As you can see, all conversions can be done with a single line, using only the Java standard collections library.

正如你所看到的,所有的转换都可以用一行来完成,只使用Java标准集合库。

The implementation of all these examples and code snippets can be found over on GitHub project – this is a Maven-based project, so it should be easy to import and run as it is.

所有这些例子和代码片段的实现都可以在GitHub项目上找到 – 这是一个基于Maven的项目,所以应该很容易导入并按原样运行。