Convert String or String Array to HashMap in Java Example

This example shows how to convert String to HashMap object. The example also shows how to convert String array to HashMap using for loop and the split method.

How to convert String to HashMap object in Java?

Suppose you have a String object containing the following content.

The string contains multiple employees separated by a comma and each employee contains id and name separated by a colon. You want to convert the string to a map object so that each employee id becomes the key of the HashMap and name becomes the value of the HashMap object.

The below example shows how to do the conversion using the string split method.


Using Java 8

The below given code does the same but using Java 8 stream.


How to convert String Array to HashMap object in Java?

If you have an array containing the data that you want to convert to the HashMap, you can use the below given code.


How to convert two arrays containing keys and values to HashMap?

If you have two arrays, one array containing keys and other containing values, you can convert them to a map object as given below.


Both the arrays should of the same size for the above example to work.

This example is a part of the HashMap in Java tutorial.

Please let me know your views in the comments section below.

About the author



My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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