Hey there!
Welcome to ClearUrDoubt.com.
In this post, we will look at the program to convert a String into a Map in Java.
Consider if a String is having KeyValuePairs delimited by another character, we can split the string and load them into a Map instance.
Eg.
input = “1=ONE,2=TWO,3=THREE,4=FOUR”
we would like to load it into a Map instance as below
{{1 -> “ONE”}, {2 -> “TWO”}, {3 -> “THREE”}, {4 -> “FOUR”}}
Let’s look at the program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
/** * Author: Sai Gowtham Badvity * Program to convert a String into a Java Map structure * */ package com.clearurdoubt; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.TreeMap; /* * StringToMap will convert a KeyValuePairsString into a TreeMap */ public class StringToMap { public static void main(String[] args) { String input = "1=ONE,2=TWO,3=THREE,4=FOUR"; // consider the input with , delimited KeyValuePairs List<String> pairs = Arrays.asList(input.split(",")); // Split the String into list of Pairs Map<Integer,String> mappers = new TreeMap<>(); // Create a TreeMap as we want to store the keys in sorted order for(String entry : pairs) // loop through the pairs { String[] pair = entry.split("="); // Split the entry into Key and Value mappers.put(Integer.parseInt(pair[0]), pair[1]); // Add the key & value to TreeMap. } // Display the TreeMap elements System.out.println("TreeMap Elements:\n"); for(Integer key : mappers.keySet()) { System.out.println(key + "=" + mappers.get(key)); } } } |
Output:
Please let me know in case of any queries.
Happy Learning :).