Home > Tutorial > Java ArrayList to HashMap Example

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>();
		//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

Posted by


I have been a software developer for twenty years now focusing on writing high quality Java applications. If you are in a programming field, you know that technology is constantly changing. You have to keep current or you will get left behind!

You may also like...

Leave a Reply

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

Copyright © 2018 JavaCodeDepot