Converting HashMap to ArrayList in Java Example

Method 1:
You can convert HashMap to ArrayList by simply iterating hashmap keys or values and you can add to arraylist.

HashMap to ArrayList Java Program:

package in.javadomain;

import java.util.ArrayList;
import java.util.HashMap;

public class HashMapTOArrayList {

	public static void main(String[] args) {
		HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
		hashMap.put(1, "Google");
		hashMap.put(2, "Facebook");
		hashMap.put(3, "Youtube");
		for(Object hashMapValue : hashMap.entrySet()){
			System.out.println("Printing From HashMap:  "+hashMapValue);
		}

		ArrayList Keys = new ArrayList();
		for (Object key : hashMap.keySet()) {
			Keys.add(key.toString());
		}
		for(Object arrayListValue : Keys){
			System.out.println("Printing Keys From ArrayList:  "+arrayListValue);
		}

		ArrayList values = new ArrayList();
		for (Object value : hashMap.values()) {
			values.add((String) value);
		}
		for(Object arrayListValue : values){
			System.out.println("Printing Values From ArrayList:  "+arrayListValue);
		}

	}

}

Output:

Printing From HashMap:  1=Google
Printing From HashMap:  2=Facebook
Printing From HashMap:  3=Youtube
Printing Keys From ArrayList:  1
Printing Keys From ArrayList:  2
Printing Keys From ArrayList:  3
Printing Values From ArrayList:  Google
Printing Values From ArrayList:  Facebook
Printing Values From ArrayList:  Youtube

 

 

Method 2:
You can directly move hashmap keys (using keySet()) and values (using values()) methods.

HashMap to ArrayList Java Program:

package in.javadomain;

import java.util.ArrayList;
import java.util.HashMap;

public class HashMapTOArrayList {

	public static void main(String[] args) {
		HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
		hashMap.put(1, "Google");
		hashMap.put(2, "Facebook");
		hashMap.put(3, "Youtube");
		for(Object hashMapValue : hashMap.entrySet()){
			System.out.println("Printing From HashMap:  "+hashMapValue);
		}

		ArrayList Keys = new ArrayList(hashMap.keySet());
		for(Object arrayListValue : Keys){
			System.out.println("Printing Keys From ArrayList:  "+arrayListValue);
		}

		ArrayList values = new ArrayList(hashMap.values());
		for(Object arrayListValue : values){
			System.out.println("Printing Values From ArrayList:  "+arrayListValue);
		}

	}

}

Output:

Printing From HashMap:  1=Google
Printing From HashMap:  2=Facebook
Printing From HashMap:  3=Youtube
Printing Keys From ArrayList:  1
Printing Keys From ArrayList:  2
Printing Keys From ArrayList:  3
Printing Values From ArrayList:  Google
Printing Values From ArrayList:  Facebook
Printing Values From ArrayList:  Youtube

Recommended Book:
Java Generics and Collections 1st Edition

426 total views, 4 views today

Leave a Reply

Your email address will not be published. Required fields are marked *