HomeSearch

Java Convert HashMap to ArrayList

This Java example page uses a HashMap and converts it to an ArrayList with the entrySet method.
Convert HashMap, ArrayList. The HashMap collection supports fast lookups. But with an ArrayList we can sort and iterate over elements more efficiently.
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.

ArrayList: We create an ArrayList of Entry elements. The Entry has the same key and value types as the HashMap we just created.

EntrySet: Use call addAll() on the ArrayList to add the entire entrySet to it. The ArrayList now contains all the HashMap's elements.

Java program that converts HashMap to ArrayList 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); } } } Output 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.For

GetKey, getValue: To get keys and values (in this example, Integers and Strings) we must use getKey and getValue on each Entry.

A summary. 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.ArrayList
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls