How to convert a HashMap to an ArrayList
Conversion of HashMap to ArrayList
A HashMap contains key-value pairs, there are three ways to convert a HashMap to an ArrayList:
-
Converting the HashMap keys into an ArrayList.
-
Converting the HashMap values into an ArrayList.
-
Converting the HashMap key-value pairs into an ArrayList.
The implementation of these three methods is shown below:
import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.Map.Entry;class HashMapToArrayListConversion {public static void main(String args[]){// HashMap with Country as key and capital as valueHashMap<String,String> countryCapitalMap=new HashMap<String,String>();countryCapitalMap.put("USA","Washington");countryCapitalMap.put("Bangladesh","Dhaka");countryCapitalMap.put("France","Paris");countryCapitalMap.put("England","London");countryCapitalMap.put("Russia","Moscow");System.out.println("-----------------------------");// Creating ArrayList from KeysArrayList<String> keysArrayList=new ArrayList<String>(countryCapitalMap.keySet());System.out.println("Countries (Keys) are: ");for (String country: keysArrayList) {System.out.println(country);}System.out.println("-----------------------------");//Creating ArrayList from ValuesArrayList<String> valuesArrayList=new ArrayList<String>(countryCapitalMap.values());System.out.println("Capital (Values) are: ");for (String capital:valuesArrayList) {System.out.println(capital);}System.out.println("-----------------------------");//Creating ArrayList from Entry setArrayList <Entry <String,String>> entryArrayList=new ArrayList<Entry<String,String>>(countryCapitalMap.entrySet());for (Entry <String, String> entry:entryArrayList) {System.out.println("Country: "+ entry.getKey()+ " and Capital: "+entry.getValue());}System.out.println("-----------------------------");}}
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved