To retrieve all values from the keys of a HashMap
and store them in an ArrayList
in Java, you can iterate through the keys of the HashMap
and add the corresponding values to the ArrayList
. Here's how you can do it:
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Main { public static void main(String[] args) { // Create a HashMap Map<String, Integer> hashMap = new HashMap<>(); // Populate the HashMap with key-value pairs hashMap.put("Key1", 100); hashMap.put("Key2", 200); hashMap.put("Key3", 300); // Create an ArrayList to store the values List<Integer> valuesList = new ArrayList<>(); // Iterate through the keys and add corresponding values to the ArrayList for (String key : hashMap.keySet()) { Integer value = hashMap.get(key); valuesList.add(value); } // Now, valuesList contains all the values from the HashMap keys System.out.println(valuesList); } }
In this example:
We create a HashMap
named hashMap
and populate it with key-value pairs.
We create an ArrayList
named valuesList
to store the values associated with the keys from the HashMap
.
We iterate through the keys of the HashMap
using a for-each loop.
For each key, we use hashMap.get(key)
to retrieve the corresponding value, and we add that value to the valuesList
.
Finally, valuesList
contains all the values from the HashMap
keys, and we print it.
The output will be:
[100, 200, 300]
Now, valuesList
contains all the values from the HashMap
keys as elements in the ArrayList
.
spam-prevention user-roles pdf-viewer cancellationtokensource oop spring-transactions justify kafka-producer-api spring-config C++