Algorithm


  1. Initialize an empty list to store key-value pairs:

    • List<KeyValueType> resultList = new ArrayList<>();
  2. Iterate over the entries of the Map:

    • for each entry in map.entrySet()
  3. Extract key and value from each entry:

    • KeyType key = entry.getKey();
    • ValueType value = entry.getValue();
  4. Add key-value pair to the list:

    • resultList.add(new KeyValueType(key, value));
  5. After iterating through all entries, the list (resultList) will contain elements from the Map.

  6. Return the resulting list:

    • return resultList;

Note: Adjust the type names (KeyType, ValueType, KeyValueType) based on the actual types used in your Map.

 

Code Examples

#1 Code Example- Convert Map to List

Code - Java Programming

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 valueList = new ArrayList(map.values());

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

    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Key List: [1, 2, 3, 4, 5]
Value List: [a, b, c, d, e]

#2 Code Example- Convert Map to List using stream

Code - Java Programming

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 valueList = map.values().stream().collect(Collectors.toList());

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

    }
}
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Java Programing Example to Convert Map (HashMap) to List-DevsEnv