Java ArrayList to HashMap Example

You can easily convert or populate a Java HashMap using the contents of an existing Java ArrayList. Keep in mind the Java ArrayList does not maintain a unique list of elements. The Java HashMap on the other hand will keep the key values unique. If you add a duplicate key, it will store the value of the most recent put.


Java ArrayList to HashMap Source Code

package com.jcd.java.tutorials;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JavaArrayListToHashMap 
{

	public static void main(String[] args) 
	{
		//Create new ArrayList that holds a collection of Strings
		List<String> jcdList = new ArrayList<String>();
		jcdList.add("Java");
		jcdList.add("Code");
		jcdList.add("Depot");
		jcdList.add("Com");
		
		//Create new Hashmap of type String,String
		Map<String,Integer> jcdMap = new HashMap<String,Integer>();
		
		//Loop through  each alement in the ArrayList and insert into HashMap
		for(String jcdString : jcdList) 
		{
			jcdMap.put(jcdString, jcdString.length());
		}
		
		//Now loop through each key,pair in jcdMap
		for (Map.Entry<String,Integer> jcdEntry : jcdMap.entrySet()) 
		{
			System.out.println("Key="+jcdEntry.getKey()+" Value="+jcdEntry.getValue());
		}
	}
}


Java ArrayList to HashMap Output

Key=Com Value=3
Key=Java Value=4
Key=Depot Value=5
Key=Code Value=4


Add a Comment

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