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 value HashMap<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 Keys ArrayList<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 Values ArrayList<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 set ArrayList <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("-----------------------------"); } }
RELATED TAGS
View all Courses