Core Java

Get ArrayLists of Values and Keys from a HashMap in Java

In Java, the HashMap is a commonly used data structure that stores keys-value pairs. Sometimes, we may need to extract the keys and values from a HashMap and store them in more convenient data structures like ArrayList. The objective of this article is to provide a guide on how to retrieve keys and values as ArrayLists from a HashMap in Java.

1. Obtaining Views from a Map

The Collections framework provides methods that allow us to obtain views from a Map. The methods listed below allow us to view the set of keys, the Collection of values, and the set of key-value pairs in a Map. They are:

  • Set<k> keySet()
  • Collection<K> values()
  • Set<Map.Entry<K, V>> entrySet()

The remainder of this article will explore how these methods can be employed to obtain keys and values as ArrayLists from a HashMap in Java.

2. Using Java 8 Stream

We can use Java 8 streams to obtain values and keys as ArrayLists from a HashMap.

2.1 Convert the keys of a HashMap into an ArrayList using Java 8 Stream

The code listing below shows the steps to convert the keys of a HashMap into an ArrayList using Java Streams:

public class HashMapKeysToArrayList {

    public static void main(String[] args) {
        // Create a HashMap
        HashMap<Integer, String> fruits = new HashMap<Integer, String>();

        // Populate the HashMap with key-value pairs
        fruits.put(1, "Apple");
        fruits.put(2, "Banana");
        fruits.put(3, "Cherry");
        fruits.put(4, "Grape");
        fruits.put(5, "Orange");

        // Use Java Streams to convert HashMap keys to an ArrayList
        List<Integer> keyList = fruits.keySet()
                .stream()
                .collect(Collectors.toCollection(ArrayList::new));

        // Now, keyList contains the keys as an ArrayList
        System.out.println("Keys as ArrayList: " + keyList);
    }
}

In the code above, we start by creating a HashMap of fruits and populating it with some key-value pairs. Next, we use the keySet() method to obtain the set of keys. We then apply a stream to the set of keys using stream() method of Java Stream API and collect the stream into an ArrayList using the Collectors.toCollection(ArrayList::new) method which collects the keys into an ArrayList.

The result is an ArrayList containing the keys from the HashMap as shown in Fig 1 below:

Fig 1: keys from a HashMap as ArrayLists in Java
Fig 1: keys from a HashMap as ArrayList

2.2 Convert the values of a HashMap into an ArrayList using Java 8 Stream

The code snippet below shows how we can convert the values of a HashMap into an ArrayList using Java 8 Streams.

// Use Java 8 Streams to convert HashMap values to an ArrayList
        List<String> valueList = fruits.values()
                .stream()
                .collect(Collectors.toList());

        // Now, valueList contains the values as an ArrayList
        System.out.println("Values as ArrayList: " + valueList);

In the code above, we update the program and use the values() method to obtain a collection of values from the HashMap and apply a stream to the collection of values using .stream() method, making use of the Java 8 Stream API. We then collect the stream into an ArrayList using the .collect(Collectors.toList()) method.

The result is an ArrayList containing the values from the HashMap.

Values as ArrayList: [Apple, Banana, Cherry, Grape, Orange]

3. Use forEach Method and Lambda Expressions

We can use the forEach method and lambda expressions to get the values and keys from a HashMap and store them in ArrayLists. Below is an example of how we can achieve this:

public class HashMapToList {

    public static void main(String[] args) {

        // Create a sample HashMap
        HashMap<Integer, String> fruits = new HashMap<>();
        fruits.put(1, "Apple");
        fruits.put(2, "Banana");
        fruits.put(3, "Cherry");
        fruits.put(4, "Grape");
        fruits.put(5, "Orange");

        // Create ArrayLists to store keys and values
        ArrayList<Integer> keysList = new ArrayList<Integer>();
        ArrayList<String> valuesList = new ArrayList<String>();

        // Use forEach and lambda expressions to populate the ArrayLists
        fruits.forEach((key, value) -> {
            keysList.add(key);
            valuesList.add(value);
        });

        // Print the keys and values
        System.out.println("Keys: " + keysList);
        System.out.println("Values: " + valuesList);
    }
}

In this example, we create a HashMap of fruits with Integer keys and String values. Then, we create two ArrayLists, keyList and valueList, which we want to use to store the keys and values obtained from the HashMap.

We then use the forEach method with a lambda expression to iterate through the HashMap, extract keys and values, and add them to their respective ArrayLists.

Finally, we print the contents of the ArrayLists and the output we get from running the application code is:

Keys: [1, 2, 3, 4, 5]
Values: [Apple, Banana, Cherry, Grape, Orange]

4. Use the Constructor of an ArrayList

To get both the keys and values from a HashMap and store them in separate ArrayList objects using the ArrayList constructor, we can use the following code:

public class ArrayListConstructor {

    public static void main(String[] args) {
        
        // Create a sample HashMap
        HashMap<Integer, String> fruits = new HashMap<>();
        fruits.put(1, "Apple");
        fruits.put(2, "Banana");
        fruits.put(3, "Cherry");
        fruits.put(4, "Grape");
        fruits.put(5, "Orange");
        
        // Get the keys from the HashMap
        Set<Integer> keys = fruits.keySet();
        
        // Get the Collection of values from the HashMap 
        Collection<String> values = fruits.values();
        
        // Create an ArrayList of keys 
        ArrayList<Integer> keysList = new ArrayList<Integer>(keys);
        
        // Create an ArrayList of values 
        ArrayList<String> valuesList = new ArrayList<>(values);
        
        // Print the keys and values
        System.out.println("Keys as ArrayList: " + keysList);
        System.out.println("Values as ArrayList: " + valuesList);
            
    }
}

In this code, we first create a HashMap named fruits and populate it. Next, we use the keySet() method of the HashMap to return the Set containing all the keys of the HashMap. Next, we use the values() method of the HashMap to obtain a Collection of all the values present in the HashMap.

Then, we use the ArrayList constructor to create ArrayList objects for keys and values separately. The first ArrayList created is named keysList is used to initialize an ArrayList for the keys while the second ArrayList named valuesList is used to initialize an ArrayList for values.

The result will be two separate ArrayLists, one containing the keys and the other containing the values from the HashMap.

5. Conclusion

In this article, we have listed techniques for displaying various views of a HashMap, and we’ve delved into several approaches, complete with code snippets, for extracting the key and value lists from a HashMap and transforming them into ArrayLists in the Java programming language.

Converting the keys and values of a HashMap into ArrayList can be useful in some programming scenarios. By following the various methods presented in this article, we can easily extract and manipulate the keys and values from a HashMap and convert them to ArrayList to meet our specific programming needs in Java.

6. Download the Source Code

This was an example of Retrieve an ArrayList of Values and Keys from a HashMap.

Download
You can download the full source code of this example here: Retrieve an ArrayList of Values and Keys from a HashMap

Omozegie Aziegbe

Omos holds a Master degree in Information Engineering with Network Management from the Robert Gordon University, Aberdeen. Omos is currently a freelance web/application developer who is currently focused on developing Java enterprise applications with the Jakarta EE framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button