Java program to convert map (hashmap) to list
Here is a Java program to convert a Map
(HashMap) to a List
:
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ConvertMapToList { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("one", 1); map.put("two", 2); map.put("three", 3); List<String> keysList = new ArrayList<>(map.keySet()); List<Integer> valuesList = new ArrayList<>(map.values()); System.out.println("Map as list of keys: " + keysList); System.out.println("Map as list of values: " + valuesList); } }
This program first creates a Map
object, map
, containing some key-value pairs. It then converts the keys and values of the map to lists using the Map.keySet()
and Map.values()
methods, respectively. The Map.keySet()
method returns a set containing the keys of the map, and the Map.values()
method returns a collection containing the values of the map.
Next, the program creates new ArrayList
objects containing the keys and values of the map, respectively. The ArrayList
constructor takes a collection as a parameter, and creates a new list containing the elements of the collection.
Note that the resulting lists do not preserve the order of the original map. If you need to preserve the order of the original map, you can use a LinkedHashMap
instead of a HashMap
, and then convert the resulting lists to LinkedList
objects, like this:
import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class ConvertLinkedHashMapToList { public static void main(String[] args) { Map<String, Integer> map = new LinkedHashMap<>(); map.put("one", 1); map.put("two", 2); map.put("three", 3); List<String> keysList = new LinkedList<>(map.keySet()); List<Integer> valuesList = new LinkedList<>(map.values()); System.out.println("Map as list of keys: " + keysList); System.out.println("Map as list of values: " + valuesList); } }
This program uses a LinkedHashMap
instead of a HashMap
to ensure that the order of the original map is preserved. It then converts the resulting lists to LinkedList
objects using the LinkedList
constructor, which creates a new linked list containing the elements of the specified collection.