Convert a Map to List in Java

Convert a Map to List in Java

In this post, we will learn as how to Convert a map to List in Java.We will see how to do this using JDK.

 

1. Conventional Method

To convert, Java Map to List, we can use the conventional constructor with ArrayList, however, there are few things to consider before we proceed with the conversion. 

 Java Map has 2 values while list contains only single value while converting Map to list, we need to take a call of converting either map values or keys, so either we will get a map of keys or list of values (we can get both by using some wrapper to have both values).

public class MapToList {

    public static void main(String[] args) {

        Map<Integer,String> map= getMap();

        //Convert Map keys to List
        List<Integer> keyList= new ArrayList<Integer>(map.keySet());
        keyList.forEach(key-> System.out.println(key));

        //Convert Map values to List
        List<String> valueList= new ArrayList<String>(map.values());
        keyList.forEach(value-> System.out.println(value));

    }

    static Map<Integer,String> getMap(){

        Map<Integer, String> sampleMap=new HashMap<Integer,String>();
        sampleMap.put(1,"Sunday");
        sampleMap.put(2,"Monday");
        sampleMap.put(3,"Tuesday");
        sampleMap.put(4,"Wednesday");

        return sampleMap;
    }
}

Output for the above programme will be

1
2
3
4

For valueList

Sunday
Monday
Tuesday
Wednesday

2. Using Java 8

We can also use Java 8 Stream API to convert Map to List in Java.

public class MapToListJava8 {

    public static void main(String[] args) {

        Map<Integer,String> map= getMap();

        List<Integer> keyList=map.keySet().stream().collect(Collectors.toList());
        keyList.forEach(key-> System.out.println(key));

        List<String> valueList=map.values().stream().collect(Collectors.toList());
        valueList.forEach(value-> System.out.println(value));
    }

    static Map<Integer,String> getMap(){

        Map<Integer, String> sampleMap=new HashMap<Integer,String>();
        sampleMap.put(1,"Sunday");
        sampleMap.put(2,"Monday");
        sampleMap.put(3,"Tuesday");
        sampleMap.put(4,"Wednesday");

        return sampleMap;
    }
}

My preference will be for the constructor based approach as it is more straight forward and easy to read rather than the Java 8 Stream API.

3. Summary

In this post, we explored as to how to convert a Map to List in Java, we learned how to convert it using a constructor and Java 8 Stream API.We can use a similar technique to convert Map to Set which we will cover in another post.

All the code of this article is available Over on Github. This is a Maven-based project.

JavaDevJournal

Hello!! I am Umesh- an engineer by profession and a photographer by passion.I like to build stuff on the web using OSS and love to capture the world through my lens.

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz