1. Introduction
In Java, a Map is a data structure that uses key-value pairs, where each key is unique. There are times when we may need to convert the keys from a Map into a List. This can be useful when we want to process the keys independently of the values, for instance, to sort the keys or to perform some operation on each key. In this blog post, we will demonstrate how to convert the keys of a Map into a List.
2. Program Steps
1. Create a Map with some key-value pairs.
2. Extract the keySet from the Map.
3. Convert the keySet to a List.
4. Print the original Map and the List of keys.
3. Code Program
import java.util.Map;
import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
public class MapKeysToList {
public static void main(String[] args) {
// Step 1: Create a Map with some key-value pairs
Map<String, Integer> fruitMap = new HashMap<>();
fruitMap.put("Apple", 10);
fruitMap.put("Banana", 20);
fruitMap.put("Cherry", 30);
// Step 2: Extract the keySet from the Map
Set<String> keySet = fruitMap.keySet();
// Step 3: Convert the keySet to a List
List<String> keyList = new ArrayList<>(keySet);
// Step 4: Print the original Map and the List of keys
System.out.println("Original Map: " + fruitMap);
System.out.println("List of Keys: " + keyList);
}
}
Output:
Original Map: {Banana=20, Cherry=30, Apple=10} List of Keys: [Banana, Cherry, Apple]
4. Step By Step Explanation
Step 1: We initialize a Map fruitMap with some key-value pairs, where keys are names of fruits, and values are their respective quantities.
Step 2: We extract the keySet from the fruitMap using the keySet() method. This method returns a Set view of the keys contained in the Map.
Step 3: The keySet is then converted into a List keyList by passing it to the constructor of the ArrayList class.
Step 4: Finally, we print the original fruitMap and the keyList containing the keys of the Map. The order of the keys in the keyList will be the same as the order in the keySet, which is not guaranteed to be in any specific order, as HashMap does not maintain the order of its elements.