Convert Map to List in Java 8 using Stream API


In Java, the Stream class was introduced as a part of the Java 8 Streams API that provides a functional way of processing collections of objects, i.e. a sequence of elements that can be processed in a functional manner.

With the help of the Stream class, you can perform various operations on collections like filtering, mapping, sorting, reducing, and more, without modifying the original collection.


Convert Map<K,V> as List<E>

To convert a Map to a List in Java 8 using Stream,

Step 1: We can use the entrySet() method of the Map interface to get a set of the map's key-value pairs.

Step 2: We can then use the stream() method to convert the set to a stream,

Step 3: We use the map() method to transform each entry into an object of your desired type

Step 4: Lastly, we can make use of the collect() method to collect the stream into a List.

Example:
package org.example;


import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 * Code Example in Java 8 to convert
 * Map to List using Stream API
 *
 *
 */
public class MapToList {

    public static void main(String[] args) {

       Map<String,String> cityTempMap = new HashMap<>();

        cityTempMap.put("NYC","34");
        cityTempMap.put("Chicago","32");
        cityTempMap.put("Austin","42");
        cityTempMap.put("Huston","31");
        cityTempMap.put("Ohio","30");

        //Map to List
        List<String> cities = cityTempMap
                .entrySet() //Step 1:entrySet() to get K-V Pair
                .stream() //Step 2: Convert Set to Stream
                .map(entry -> entry.getKey()) // Step 3: Use map() to transform
                .collect(Collectors.toList()); // Step 4: Collect Stream as List

        System.out.println(cities);

    }
}
Output:

[Chicago, NYC, Ohio, Austin, Huston]

Java 8 Convert Map to List using Stream Example Output

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap