3 Ways to convert a Map to List in Java 8 - Example Tutorial

Hello guys, when you convert a Map to List in Java 8 or before, you have three choices like you can get a list of keys from Map, List of values from Map, or a List of entries from Map, which encapsulates both keys and values. The API doesn't provide these methods because Map doesn't guarantee any order and List interface guarantee ordering, like insertion order. Hence, JDK API provides an equivalent method to convert a Map to Set, like keySet() will return a set of keys and entrySet() will return a set of entries.

Since Set cannot have duplicates and Map also cannot have duplicate keys, the Set data structure seems to perfect for returning keys and entries. But, values can be duplicated in Map; hence API provides values() method which returns Collection.

Before Java 8, the problem of converting a Map to List is actually a problem of converting Map to Set and then to List, which is also not different in Java 8. Still, because of Streams and lambda expression, it seems you are doing everything in one step.

In the last article, you have learned how to convert a List to Map in Java 8, and in this article, you will learn the opposite, like converting a Map to List.

Btw, if you are new to Java world or still catching up after a long break from Java, you should join The Complete Java MasterClass course for more structured learning. It is one of the best and most up-to-date courses for Java programmers and anyone wishes to become a Java Yoda.




3 ways to convert a Map to List in Java

In reality, it's not really possible to convert a Map to List because both are different types of data structures. A Map is a collection of key-value pairs while List contains just elements. So, when we say converting a Map to List, there are three choices for us - create a List of keys, a list of values, or a list of entries that contain both key and value.

In this article, we'll take a look at all these ways to convert a Map to List using Java 8 functionalities like Stream and Lambda expression.

1. Map to List of keys

Here is a one-liner to convert a Map of Integer and String, where Integer is key, and String is the type of value, to a List of Integer, i.e. list of keys:

idToName.keySet().stream().collect(Collectors.toList());

In this code, we first get the set of keys by calling the keySet() method and them a stream of keys by calling stream() method. After that, you just need to convert the Stream to List, which we have done using Collectors.toList() method, as shown in the earlier example.

Just keep in mind that toList() can return any kind of List implementation, like ArrayList or LinkedList or even Vector, it's up to the implementation. If you want a particular implementation, like ArrayList, you can use another method called toCollection(), which accepts a Supplier to denote the implementation class.

 For example, you can convert a Map to ArrayList of keys by using the following snippet:

dToName.keySet()
        .stream()
        .collect(Collectors.toCollection(ArrayList::new));

or, you can use the below code to convert a Map to LinkedList in Java.

idToName.keySet()
        .stream()
        .collect(Collectors.toCollection(LinkedList::new))

By using this technique, you can convert a Map to ArrayList, LinkedList, Vector, or any other List implementation. If you want to learn more about Stream, I suggest you to the Java Streams API Developer Guide course on Udemy.

How to convert a Map to List in Java 8




2. Map to List to Values

Here is the one line of code to create a list of values from Map. It's very similar to the code for creating a list of keys, with only difference of using values() instead of keySet() method.

idToName.values()
        .stream()
        .collect(Collectors.toCollection(ArrayList::new))

Another subtle difference is that this list may contain duplicates because values can be repeated in a Map. If you want to create a map of unique values then you need to filter out duplicate elements and for that, you can actually collect the result in a Set instead of List and then convert the Set to List.

Alternatively, you can also use the Stream.distinct() method to filter out duplicates as shown in the following code:

idToName.values()
        .stream()
        .distinct()
        .collect(Collectors.toCollection(ArrayList::new))



3. Map to List of entries

Here is the one line of code to create a list of values from Map. You can see this code is also very similar to the previous code we have used to create a list of keys and values, the only difference is instead of using keySet() or values(), I have used the entrySet() method which returns set of entries.

idToName.entrySet()
        .stream()
        .collect(Collectors.toCollection(ArrayList::new)

This list will contain all the entries from the Map. This way, you can also convert your HashMap to LinkedHashMap to a List in Java.


4. Map of Entries to List of Objects

Now, you may have a situation where you need to create an object by using key and value from Map, like a Pair object which contains both key and values. Though you can easily use Map.Entry if you want both key and value as shown in the previous example, the new object teach you an essential technique of mapping Stream elements to other object using map() method.

idToName.entrySet()
        .stream()
        .map( e -> Pair::new)
        .collect(Collectors.toCollection(ArrayList::new))

This code example also demonstrates how you can use a lambda expression to transform your data in just a few lines of code. If you are new to a lambda expression, I highly recommend you learn this vital concept in detail.

If you need a resource, I suggest you check out  Java Functional Programming using the Lambdas and Stream course by Ranga Karnam on Udemy. It's one of the best and hand-son courses to learn these vital functional programming concepts like map, flatMap, and reduction in Java.

best course to learn Java functional programming




Important points

1) The keySet() method returns a Set of keys; you need this method because stream() is not available in java.util.Map class.

2) The entrySet() method return a Set of Map.Entry object which contains both key and value.

3) The values() method returns a Collection of values because the value can be duplicate as opposed to Set. See the difference between keySet, values, and entrySet to learn more.

4) The toList() method of Collector returns a List without any guarantees on the type, thread-safety, mutability, and serializability. It can return elements of String in an ArrayList or LinkedList or any custom implementation.

5) If you want to accumulate Stream elements into ArrayList, then you must use toCollection() method and pass ArrayList::new. This will then return an ArrayList of keys. You can use this technique to convert Map to any type of List in Java.


That's all about how to convert a Map to a List in Java 8. You have learned how to convert a Map to the ArrayList and LinkedList. You have also learned how to create a List of Keys and List of values, along with a list of entries from Map object. If you want to learn more about essential Java 8 concepts, you can check the following resources.

Further Learning
The Complete Java MasterClass
What's New in Java 8
Refactoring to Java 8 Streams and Lambdas Self- Study Workshop

Related Java 8 Tutorials

If you are interested in learning more about new features of Java 8, here are my earlier articles covering some of the important concepts of Java 8:
  • The 2020 Java Developer RoadMap (see)
  • 5 Books to Learn Java 8 from Scratch (books)
  • What is the default method in Java 8? (example)
  • How to join String in Java 8 (example)
  • Top 5 Courses to learn Functional Programming in Java (courses)
  • How to use filter() method in Java 8 (tutorial)
  • 10 Courses to learn Java for Beginners (courses)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • How to use Stream class in Java 8 (tutorial)
  • Top 5 courses to become a full-stack Java developer  (courses)
  • How to convert List to Map in Java 8 (solution)
  • Difference between abstract class and interface in Java 8? (answer)
  • 20 Examples of Date and Time in Java 8 (tutorial)
  • How to sort the map by keys in Java 8? (example)
  • How to sort the may by values in Java 8? (example)
  • 10 examples of Optionals in Java 8? (example)

Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or suggestions then please drop a comment.

P. S. - If you are keen to learn more about lambda expression and functional programming in Java but looking for a free online training course to start with then you can also check out Java 8 Functional Programming: Lambda Expressions Quickly free course on Udemy. It's completely free and you just need a free Udemy account to join this course.

No comments:

Post a Comment