Write a Java Program to Convert Map (HashMap) to List

Java Program to Convert Map (HashMap) to List

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Convert Map (HashMap) to List
Java Program to Convert Map (HashMap) to List

Write a Java Program to Convert Map (HashMap) to List

PROGRAM: Java Program to Convert Map (HashMap) to List

/*Java Program to Convert Map (HashMap) to List*/

1: Convert Map to List

import java.util.*;

public class MapList {

    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<>();
        map.put(1, "a");
        map.put(2, "b");
        map.put(3, "c");
        map.put(4, "d");
        map.put(5, "e");

        List<Integer> keyList = new ArrayList(map.keySet());
        List<String> valueList = new ArrayList(map.values());

        System.out.println("Key List: " + keyList);
        System.out.println("Value List: " + valueList);

    }
}

2: Convert Map to List using stream

import java.util.*;
import java.util.stream.Collectors;

public class MapList {

    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<>();
        map.put(1, "a");
        map.put(2, "b");
        map.put(3, "c");
        map.put(4, "d");
        map.put(5, "e");

        List<Integer> keyList = map.keySet().stream().collect(Collectors.toList());
        List<String> valueList = map.values().stream().collect(Collectors.toList());

        System.out.println("Key List: " + keyList);
        System.out.println("Value List: " + valueList);

    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *