Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

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

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.

2. Converting Using Core 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.

2.1. Using the ArrayList Constructor

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

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

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.

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

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

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:

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.

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

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

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

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.

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

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

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.

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

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

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

<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:

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.

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.

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

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

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

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.

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

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.