Converting a Java Map to a List is a very common task. Map and List are common data structures used in Java. A Map is a collection of key value pairs. While a  List is an ordered collection of objects in which duplicate values can be stored.

In this post, I will discuss different ways to convert a Map to a List.

For the example code in this post, I’ll provide JUnit tests. If you are new to JUnit, I suggest you go through my series on Unit Testing with JUnit.

Converting Map Keys to List

The Map class comes with the keyset() method that returns a Set view of the keys contained in the map. The code to convert all the keys of a Map to a Set is this.

Here is the JUnit test code.

The output on running the test in IntelliJ is this.
Test Output Java Map Key To List

Converting Map Values to List

You use the values() method of Map to convert all the values of Map entries into a List.

Here is the code to convert Map values to a List.

Here is the Junit test code.

The output on running the test in IntelliJ is this.
Test Output Map Values to List

Converting Map to List using Java 8 Streams

If you are into functional programming style, you can use streams introduced in Java 8, along with some utility classes like Collectors, which provides several useful methods to convert stream of Map entries to List.

The stream() method return a stream of the keys from the Set of the map keys that Map.keySet() returns. The collect() method of the Stream class is called to collect the results in a List.

The Collectors.toList() passed to the collect() method is a generalized approach. You can collect elements of Stream in specific collection, such as ArrayList, LinkedList, or any other List implementation. To do so, call the toColection() method, like this.

Here is the JUnit test code.

The JUnit test output in IntelliJ is this.
Test Output Java Map Keys To List with Java 8 Streams

Converting Map values to List using streams is similar. You only need to get the stream of Map values that map.values() return, like this

The test code is this.

The test output in IntelliJ is this.
Test Output Map Values To List with Stream

Converting Generic Map to List using Stream and Java Lambdas

Till now I showed using method reference with stream to perform conversion of Map to List.
I personally prefer method reference over lambda expressions because I find them clear and concise.
Also, when using collection, you will typically use generic collections and perform conversions between them.

For such collections, you can use streams with lambda expressions, like this.

The code to use method reference is this.

Here is the JUnit test code.

The JUnit test output in IntelliJ is this.

0
Share