How to convert HashMap to ArrayList in java

In this post, we will see how to convert HashMap to ArrayList in java. Many a times, you need to store keys or values into ArrayList or Store HashMap's Entry objects in ArrayList.

Java HashMap tutorial:

    HashMap in javaHashMap internal workinghash and indexfor method in HashMaphashcode and equals in javasort HashMap by keys and valuesDifference between HashMap and HashSetDifference between HashMap and HashtableHow to iterate over HashMap
Lets take an example:
1. HashMapToArrayListConversionMain.java
package org.arpit.java2blog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

public class HashMapToArrayListConversionMain {

 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("India","Delhi");
  countryCapitalMap.put("Japan","Tokyo");
  countryCapitalMap.put("France","Paris");
  countryCapitalMap.put("Russia","Moscow");


  System.out.println("-----------------------------");

  // Creating  ArrayList from Keys
  
  ArrayList<String> keysArrayList=new ArrayList<String>(countryCapitalMap.keySet());
  System.out.println("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("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("-----------------------------");

 }

}

Run it and you will get following output:
-----------------------------
Keys are: 
France
Russia
Japan
India
-----------------------------
Values are: 
Paris
Moscow
Tokyo
Delhi
-----------------------------
Country:France and  Capital:Paris
Country:Russia and  Capital:Moscow
Country:Japan and  Capital:Tokyo
Country:India and  Capital:Delhi
-----------------------------


Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012