Convert String to Map in Java

Handling key-value-based data is a common requirement in various Java applications. Often, data arrives as Strings or String arrays, and it becomes essential to convert them into Maps for efficient processing. In the same context, Map provide an easy way to access and manipulate data with key-value pairs, making them a powerful data structure for such scenarios.

In this section, we'll explore different techniques to convert Strings and String arrays into Map. We'll also discuss how to handle duplicate keys when converting String arrays to Map with Lists of values. Additionally, to ensure the correctness of our implementations.

Converting String to map

When we have a String with key-value pairs, we can convert it into a Map. The key-value pairs in the String must be separated by a delimiter, that could be any character, such as a comma, semicolon, or an equal sign.

StringToMapExample.java

Output:

Key: key1, Value: value1
Key: key2, Value: value2
Key: key3, Value: value3

Converting Array String to Map

If we have an array of Strings, where each element represents a key-value pair, we can convert it into a Map.

StringArrayToMapExample.java

Output:

Key: name, Value: John
Key: age, Value: 30
Key: city, Value: NewYork

Handling Duplicate Key

In some cases, the String array may contain duplicate keys, and we might need to store multiple values associated with each key in the Map. To achieve this, we can use a Map with Lists of values.

StringArrayToMapWithDuplicatesExample.java

Output:

Key: name, Values: [John, Smith]
Key: age, Values: [30]
Key: city, Values: [NewYork]





Latest Courses