Retrieve all values from HashMap keys in an ArrayList Java

Retrieve all values from HashMap keys in an ArrayList Java

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:

  1. We create a HashMap named hashMap and populate it with key-value pairs.

  2. We create an ArrayList named valuesList to store the values associated with the keys from the HashMap.

  3. We iterate through the keys of the HashMap using a for-each loop.

  4. For each key, we use hashMap.get(key) to retrieve the corresponding value, and we add that value to the valuesList.

  5. 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.


More Tags

spam-prevention user-roles pdf-viewer cancellationtokensource oop spring-transactions justify kafka-producer-api spring-config C++

More Java Questions

More Date and Time Calculators

More Entertainment Anecdotes Calculators

More Pregnancy Calculators

More Internet Calculators