Home
Java
Convert HashMap to ArrayList
This page was last reviewed on May 25, 2023.
Dot Net Perls
Convert HashMap, ArrayList. The HashMap collection supports fast lookups. But with an ArrayList we can sort and iterate over elements more efficiently.
HashMap
ArrayList
To convert a HashMap to an ArrayList we can create an ArrayList and then populate it. We use the entrySet method. We must introduce the Entry class.
An example. To begin we create a HashMap and specify Integer keys and String values. We then use put() to add 3 entries to the HashMap.
Start We create an ArrayList of Entry elements. The Entry has the same key and value types as the HashMap we just created.
Next We call addAll() on the ArrayList to add the entire entrySet to it. The ArrayList now contains all the HashMap's elements.
import java.util.HashMap; import java.util.Map.Entry; import java.util.ArrayList; public class Program { public static void main(String[] args) { // Create a HashMap. HashMap<Integer, String> hash = new HashMap<>(); hash.put(100, "one-hundred"); hash.put(1000, "one-thousand"); hash.put(50, "fifty"); // Use Entry type. // ... Create an ArrayList and call addAll to add the entrySet. ArrayList<Entry<Integer, String>> array = new ArrayList<>(); array.addAll(hash.entrySet()); // Loop over ArrayList of Entry elements. for (Entry<Integer, String> entry : array) { // Use each ArrayList element. int key = entry.getKey(); String value = entry.getValue(); System.out.println("Key = " + key + "; Value = " + value); } } }
Key = 50; Value = fifty Key = 100; Value = one-hundred Key = 1000; Value = one-thousand
Notes, for-loop. In the above example we use a for-loop on the ArrayList. It is easier to iterate over an ArrayList than a HashMap. We access the keys and values from each Entry.
Tip To get keys and values (in this example, Integers and Strings) we must use getKey and getValue on each Entry.
A HashMap offers important advantages for lookups. But with an ArrayList, we have better looping and sorting. We can convert a HashMap to an ArrayList with addAll() and entrySet.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 25, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.