Algorithm
-
Initialize an empty list to store key-value pairs:
List<KeyValueType> resultList = new ArrayList<>();
-
Iterate over the entries of the Map:
for each entry in map.entrySet()
-
Extract key and value from each entry:
KeyType key = entry.getKey();
ValueType value = entry.getValue();
-
Add key-value pair to the list:
resultList.add(new KeyValueType(key, value));
-
After iterating through all entries, the list (
resultList
) will contain elements from the Map. -
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
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
Demonstration
Java Programing Example to Convert Map (HashMap) to List-DevsEnv