In Java, you can easily convert a Map to a List in Java. You can convert it into two separate list objects, one that contains key values and one that contains map values. This is because Objects of the Map class contain a key and a value pair.
Let's take a look at the following simple steps of converting a Map into a List in Java:
Step 1: In the first step, create a Map object.
Step 2: Insert the key and value pairs into it using the put() method
Step 3: To hold the keys of the map, create an ArrayList of integer type. In its constructor, call the keySet() method.
Step 4: To hold the values of the map, create an ArrayList of String type. In its constructor, call the values() method of the Map class.
Step 5: We have now converted our Map into a List. Just, Print out both lists.
In this example, we are converting a map to a List in Java using the above steps
import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class Convert_map_to_List { public static void main(String[] args) { Map<Integer, String> OriginalMap = new HashMap<>(); OriginalMap.put(1, "Java"); OriginalMap.put(2, "PHP"); OriginalMap.put(3, "Python"); OriginalMap.put(4, "JavaScript"); ArrayList<Integer> keyList = new ArrayList<Integer>(OriginalMap.keySet()); ArrayList<String> valueList = new ArrayList<String>(OriginalMap.values()); System.out.println("Map Content ::"+keyList); System.out.println("Our List ::"+valueList); } } |
Output:
Map Content ::[1, 2, 3, 4] Our List ::[Java, PHP, Python, JavaScript] |
Keywords: How to convert Map to a List in Java , Java Collections, Java
Article Contributed By :
|
|
|
|
110 Views |