java

Convert Hashmap to List in Java

HashMap is a class in Java that implements the Map interface. This is an unordered and unsorted Map, while ArrayList implements the List interface and keeps the insertion order. In this tutorial, we are going to see how to convert a Map into a List.
 

Example 1: Convert a Map to a List
import java.util.*;

public class MapToList {

    public static void main(String[] args) {

         Map<Integer, String> map = new HashMap<>();
         map.put(1, "A");
         map.put(2, "B");
         map.put(3, "C");

        //kList for keys
        List<Integer> kList = new ArrayList(map.keySet());
        //vList for values
        List<String> vList = new ArrayList(map.values());

        System.out.println("List of keys: " + kList);
        System.out.println("List of values: " + vList);

    }
}

Output:

List of keys: [1, 2, 3]
List of values: [A, B, C]

 

 

Example 2: convert a Map to a List using Streams
import java.util.*;
import java.util.stream.*;

public class MapToList {

    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<>();
        map.put(1, "A");
        map.put(2, "B");
        map.put(3, "C");

        //kList for keys
        List<Integer> kList = 
        map.keySet().stream().collect(Collectors.toList());
        //vList for values
        List<String> vList = 
        map.values().stream().collect(Collectors.toList());

        System.out.println("List of keys: " + kList);
        System.out.println("List of values: " + vList);

    }
}

The output of the program is same as the output of Example 1.
 
Output:

List of keys: [1, 2, 3]
List of values: [A, B, C]
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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