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.

package org.example;

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

 * 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<>();


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



[Chicago, NYC, Ohio, Austin, Huston]

Java 8 Convert Map to List using Stream Example Output

Have Questions? Post them here!

Top Hashtags: