Skip to content

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.

Output

Using Java 8

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

Output

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.

Output

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.

Output

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

Leave a Reply

Your email address will not be published.