
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.
Commercials Cooperation Advertisements:
(1) IT Teacher IT Freelance

立刻註冊及報名電腦補習課程吧!
电子计算机 -教育 -IT 電腦班” ( IT電腦補習 ) 提供一個方便的电子计算机 教育平台, 為大家配對信息技术, 電腦 老師, IT freelance 和 programming expert. 讓大家方便地就能找到合適的電腦補習, 電腦班, 家教, 私人老師.
We are a education and information platform which you can find a IT private tutorial teacher or freelance.
Also we provide different information about information technology, Computer, programming, mobile, Android, apple, game, movie, anime, animation…
(2) ITSec
www.ITSeceu.uk
Secure Your Computers from Cyber Threats and mitigate risks with professional services to defend Hackers.
ITSec provide IT Security and Compliance Services, including IT Compliance Services, Risk Assessment, IT Audit, Security Assessment and Audit, ISO 27001 Consulting and Certification, GDPR Compliance Services, Privacy Impact Assessment (PIA), Penetration test, Ethical Hacking, Vulnerabilities scan, IT Consulting, Data Privacy Consulting, Data Protection Services, Information Security Consulting, Cyber Security Consulting, Network Security Audit, Security Awareness Training.
Contact us right away.
Email (Prefer using email to contact us):
SalesExecutive@ITSec.vip