Converting HashMap Values to an ArrayList in Java – 在 Java 中将 HashMap 值转换为 ArrayList

最后修改: 2023年 10月 2日

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

1. Overview

1.概述

In this short tutorial, we’ll shed light on how to convert HashMap values into an ArrayList in Java.

在本简短教程中,我们将介绍如何在 Java 中将 HashMap 值转换为 ArrayList 值。

First, we’ll explain how to do it using core Java methods. Then, we will demonstrate how to tackle our central puzzle using external libraries such as Guava.

首先,我们将介绍如何使用核心 Java 方法来实现这一目标。然后,我们将演示如何使用外部库(如 Guava)来解决我们的核心难题。

2. Converting Using Core Java

2.使用核心 Java 进行转换

Converting a HashMap to an ArrayList is a common task. In this section, we’ll cover different ways to do this using Java classes and methods.

HashMap 转换为 ArrayList 是一项常见任务。在本节中,我们将介绍使用 Java 类和方法进行转换的不同方法。

2.1. Using the ArrayList Constructor

2.1.使用 ArrayList 构造函数

ArrayList constructor provides the most common and easiest way to convert a HashMap to an ArrayList.

ArrayList 构造函数提供了将 HashMap 转换为 ArrayList 的最常用、最简单的方法。

The basic idea here is to pass the values of the HashMap as a parameter to the ArrayList constructor:

这里的基本思想是将 HashMap 的值作为参数传递给 ArrayList 构造函数

ArrayList<String> convertUsingConstructor(HashMap<Integer, String> hashMap) {
    if (hashMap == null) {
        return null;
    }
    return new ArrayList<String>(hashMap.values());
}

As we can see, we started by checking if our HashMap is null to make our method null-safe. Then, we used the values() method, which returns a collection view of the values contained in the given HashMap.

正如我们所见,我们首先检查 HashMap 是否为 null,以确保我们的方法是 null 安全的。然后,我们使用 values() 方法,该方法返回给定 HashMap 中包含的值的集合视图。

Now, let’s confirm this using a test case:

现在,让我们用一个测试用例来确认一下:

public class HashMapToArrayListConverterUtilsUnitTest {

    private HashMap<Integer, String> hashMap;

    @Before
    public void beforeEach() {
        hashMap = new HashMap<>();
        hashMap.put(1, "AAA");
        hashMap.put(2, "BBB");
        hashMap.put(3, "CCC");
        hashMap.put(4, "DDD");
    }

    @Test
    public void givenAHashMap_whenConvertUsingConstructor_thenReturnArrayList() {
        ArrayList<String> myList = HashMapToArrayListConverterUtils.convertUsingConstructor(hashMap);
        assertThat(hashMap.values(), containsInAnyOrder(myList.toArray()));
    }

    // ...
}

As expected, the test passed with success.

不出所料,测试成功通过。

2.2. Using the addAll() Method

2.2.使用 addAll() 方法

The addAll() method is another great option to consider if we want to convert a HashMap to an ArrayList.

如果我们要将 HashMap 转换为 ArrayList, addAll() 方法是另一个不错的选择。

As the name implies, this method allows to add all of the elements in the specified collection to the end of the list.

顾名思义,此方法允许将指定集合中的所有元素添加到列表末尾

Now, let’s exemplify the use of the addAll() method:

现在,让我们举例说明 addAll() 方法的使用:

ArrayList<String> convertUsingAddAllMethod(HashMap<Integer, String> hashMap) {
    if (hashMap == null) {
        return null;
    }

    ArrayList<String> arrayList = new ArrayList<String>(hashMap.size());
    arrayList.addAll(hashMap.values());

    return arrayList;
}

As shown above, we first initialized the ArrayList with the same size as the passed HashMap. Then, we called the addAll() method to append all the values of the HashMap.

如上所示,我们首先初始化了 ArrayList ,其大小与传递的 HashMap 相同。然后,我们调用 addAll() 方法追加 HashMap 的所有值。

Again, let’s add a new test case to verify that everything works as expected:

让我们再次添加一个新的测试用例,以验证一切都能按预期运行:

@Test
public void givenAHashMap_whenConvertUsingAddAllMethod_thenReturnArrayList() {
    ArrayList<String> myList = HashMapToArrayListConverterUtils.convertUsingAddAllMethod(hashMap);

    assertThat(hashMap.values(), containsInAnyOrder(myList.toArray()));
}

Unsurprisingly, the test case passes with success.

不出所料,测试用例成功通过。

2.3. Using the Stream API

2.3.使用流应用程序接口

Java 8 comes with a lot of new features and enhancements. Among these features, we find the Stream API.

Java 8 提供了许多新功能和增强功能。在这些功能中,我们发现了 Stream API

So, let’s illustrate how to use the stream API to convert a HashMap to an ArrayList using a practical example:

因此,让我们通过一个实际示例来说明如何使用流 API 将 HashMap 转换为 ArrayList

ArrayList<String> convertUsingStreamApi(HashMap<Integer, String> hashMap) {
    if (hashMap == null) {
        return null;
    }

    return hashMap.values()
      .stream()
      .collect(Collectors.toCollection(ArrayList::new));
}

In a nutshell, we created a Stream from the values of the given HashMap. Then, we used the collect() method with the Collectors class to create a new ArrayList holding the elements of our Stream.

简而言之,我们根据给定 HashMap 的值创建了一个 Stream 流。然后,我们使用 Collectors 类中的 collect() 方法创建一个新的 ArrayList 来保存 Stream 中的元素。

As always, let’s confirm our method using a new test case:

像往常一样,让我们用一个新的测试用例来确认我们的方法:

@Test
public void givenAHashMap_whenConvertUsingStreamApi_thenReturnArrayList() {
    ArrayList<String> myList = HashMapToArrayListConverterUtils.convertUsingStreamApi(hashMap);

    assertThat(hashMap.values(), containsInAnyOrder(myList.toArray()));
}

2.4. Using a Traditional Loop

2.4.使用传统循环

Alternatively, we can use a traditional for loop to achieve the same objective:

或者,我们也可以使用传统的 for 循环来实现同样的目标:

ArrayList<String> convertUsingForLoop(HashMap<Integer, String> hashMap) {
    if (hashMap == null) {
        return null;
    }

    ArrayList<String> arrayList = new ArrayList<String>(hashMap.size());
    for (Map.Entry<Integer, String> entry : hashMap.entrySet()) {
        arrayList.add(entry.getValue());
    }

    return arrayList;
}

As we can see, we iterated through the entries of the HashMap. Furthermore, we used the entry.getValue() on each Entry to get its value. Then, we used the add() method to add the returned value to the ArrayList.

我们可以看到,我们遍历了 HashMap 的条目。此外,我们在每个 Entry 上使用 entry.getValue() 来获取其值。然后,我们使用 add() 方法将返回值添加到 ArrayList 中。

Lastly, let’s test our method using another test case:

最后,让我们用另一个测试用例来测试我们的方法:

@Test
public void givenAHashMap_whenConvertUsingForLoop_thenReturnArrayList() {
    ArrayList<String> myList = HashMapToArrayListConverterUtils.convertUsingForLoop(hashMap);

    assertThat(hashMap.values(), containsInAnyOrder(myList.toArray()));
}

3. Using Guava

3.使用番石榴

Guava offers a rich set of utility classes that simplify common programming tasks such as collection manipulation.

Guava 提供了丰富的实用程序类,可简化集合操作等常见编程任务。

First, we need to add the Guava dependency to the pom.xml file:

首先,我们需要将 Guava 依赖关系添加到 pom.xml 文件中:

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

Guava Library provides the Lists utility class mainly to work with lists. So, let’s see it in practice:

Guava 库提供了 Lists 实用程序类,主要用于处理列表。因此,让我们来看看它的实际应用:

public ArrayList<String> convertUsingGuava(HashMap<Integer, String> hashMap) {
    if (hashMap == null) {
        return null;
    }
    EntryTransformer<Integer, String, String> entryMapTransformer = (key, value) -> value;

    return Lists.newArrayList(Maps.transformEntries(hashMap, entryMapTransformer)
      .values());
}

The Lists class comes with the newArrayList() method, which creates a new ArrayList based on the given elements.

Lists类带有newArrayList()方法,该方法可根据给定的元素创建新的ArrayList

As shown above, we used a custom EntryTransformer to get the value from the key-value pair. Then, we passed our transformer to the Maps.transformEntries() method alongside the HashMap.

如上所示,我们使用自定义 EntryTransformer 从键值对中获取值。然后,我们将转换器与 HashMap 方法一起传递给 Maps.transformEntries() 方法。

That way, we tell Guava to create a new ArrayList from the values of the HashMap.

这样,我们就可以告诉 Guava 从 HashMap 的值创建一个新的 ArrayList

Finally, we’ll add a test case for our method:

最后,我们将为我们的方法添加一个测试用例:

@Test
public void givenAHashMap_whenConvertUsingGuava_thenReturnArrayList() {
    ArrayList<String> myList = HashMapToArrayListConverterUtils.convertUsingGuava(hashMap);

    assertThat(hashMap.values(), containsInAnyOrder(myList.toArray()));
}

4. Conclusion

4.结论

In this article, we explored different ways to convert a HashMap to an ArrayList in Java.

在本文中,我们探讨了在 Java 中将 HashMap 转换为 ArrayList 的不同方法。

We looked at some ways to do this using the core Java. Then, we demonstrated how to use third-party libraries to accomplish the same thing.

我们了解了使用 Java 核心实现这一目标的一些方法。然后,我们演示了如何使用第三方库来实现同样的功能。

As always, the code used in this article can be found over on GitHub.

与往常一样,本文中使用的代码可以在 GitHub 上找到