Convert String to Map Java

Convert String to Map Java | As we all know the string is the collection of a sequence of characters and a Map is an interface under the collection framework which stores the elements in the key, value pair form.

The map operations can be done with a key or if you want to retrieve the value then you can use the respective key to do so. Also, the map only stores unique key values, therefore, no duplicate values are allowed on the map. Now this blog, teaches you how to convert the string to a map. The string has a particular type of elements but in the map, we need to store the elements in the form of key and value pairs. Analyzing this problem might feel difficult but this blog helps you to solve it in an easy way. In this blog, we use two methods to do so. Observe the below examples you might get more clarity.

Example:-
1. String = “Apple:1, Banana:2, Mango:3”
Map = {Apple=1, Mango=3, Banana=2}
2. String array = { “Apple”, “Pomegranate”, “Strawberries”, “Watermelons”, “Green Grapes” }
Integer array = { 1, 2, 3, 4, 5 }
Map = {1=Apple, 2=Pomegranate, 3=Strawberries, 4=Watermelons, 5=Green Grapes}
In this section, we will implement both the above methods the first method is converting a single string to the map the next one is taking two string array for key and value and then converting it to a map.

Apart from these two examples, we will also see how to convert JSON string to map using Jackson API. Example:-
Json String = {“apple”:”1″,”banana”:”2″,”pomegranate”:”4″,”Mango”:”6″}
Map: {apple=1 , banana=2, pomegranate=4, Mango=6}.

Java Program To Convert String To Map

import java.util.HashMap;
import java.util.Map;

public class Main {
   public static void main(String[] args) {
      String data = "Apple:1, Banana:2, Mango:3";
      Map<String, String> map = new HashMap<String, String>();

      String fruits[] = data.split(",");
      for (String fruit : fruits) {
         String string1[] = fruit.split(":");
         String string2 = string1[0].trim();
         String string3 = string1[1].trim();
         map.put(string2, string3);
      }

      System.out.println("String: " + data);
      System.out.println("Map: " + map);
   }
}

Output:-

String: Apple:1, Banana:2, Mango:3
Map: {Apple=1, Mango=3, Banana=2}

In the above program to convert string to map Java, the string contains the fruit name and value which are separated by a colon (:), and each fruit is separated by a comma. Therefore first we have split based on the comma and then we have fetched the name and value. Both data had been placed on the map as key & value.

Convert String To Map Java

Now we will see an example where we have a string array and an integer array. Using these two arrays we want to create a map. In the map, we will make integer value as key and string element as value.

import java.util.HashMap;
import java.util.Map;

public class Main {
   public static void main(String[] args) {

      String fruits[] = { "Apple", "Pomegranate", 
        "Strawberries", "Watermelons", "Green Grapes" };
      Integer number[] = { 1, 2, 3, 4, 5 };

      Map<Integer, String> fruitMap = new HashMap<Integer, String>();
      for (int i = 0; i < fruits.length && i < number.length; i++) {
         fruitMap.put(number[i], fruits[i]);
      }

      System.out.println("Map: " + fruitMap);
   }
}

Output:-

Map: {1=Apple, 2=Pomegranate, 3=Strawberries, 4=Watermelons, 5=Green Grapes}

Convert JSON String to Map Java

To convert JSON string to map we are going to use Jackson API. For this, we will need the following dependencies:- Jackson-core, Jackson-databind & Jackson-annotations.

We have the following JSON which needs to be converted into the map.

{
  "apple": "1",
  "banana": "2",
  "pomegranate": "4",
  "Mango": "6"
}

Java Program to Convert JSON String to Map using Jackson API

import java.util.HashMap;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
   public static void main(String[] args) {
      String data = 
         "{\"apple\":\"1\",\"banana\":\"2\","
         + "\"pomegranate\":\"4\",\"Mango\":\"6\"}";
      System.out.println("String: " + data);
      
      try {
         HashMap<String, Integer> map = stringToMap(data);
         System.out.println("Map: " + map);
      } catch (JsonMappingException e) {
         e.printStackTrace();
      } catch (JsonProcessingException e) {
         e.printStackTrace();
      }
   }

   private static HashMap<String, Integer> stringToMap(String data) 
         throws JsonMappingException, JsonProcessingException {
      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.readValue(data, 
            new TypeReference<HashMap<String, Integer>>(){});
   }
}

Output:-

String: {“apple”:”1″,”banana”:”2″,”pomegranate”:”4″,”Mango”:”6″}
Map: {banana=2, apple=1, pomegranate=4, Mango=6}

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.