Converting Java Map to List

Converting Java Map to List

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.

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.

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.