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
.
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
of Entry elements. The Entry has the same key and value types as the HashMap
we just created.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
for
-loopIn 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.
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
.