How To Convert String Into Hashmap

What is hashmap?

A Hashmap is like a foreign language dictionary. You have a key which you use to look up corresponding value.The Hashmap uses a hash of the key for lookups . This is very handy , in the conditions when you have to store a value which has a distinct key and can be identified by the unique key.In hashmap using a key and a value, you can store the value in Map object,we can retrieve it later by using it’s key. Best example of Hashmap is a phone book where we can find the details , based on the name of the person, locality, area,country and other details.So in a nutshell it is an organized storage of data.

Now the point I am going to focus is , sometimes we need to convert a string in a map, like , user has entered some data and you need to use a specific part of the string, for doing operations.

The steps which should be followed are-

1. Get the string which needs to be coverted into a map, be clear with the format in which the string is coming for conversion, that is , you should have a clear perception of the pattern of the string For Instance: String is in format {‘a=value1′,’b=value2′,’c=value3’} or could be like a=value1&b=value2&b=value3 .

2. We need to figure out as what is the seperator between the two values in the string , like ‘%’ , ‘\’ , ‘!’ ,etc.for the above stated two instances the seperator is ‘,’ for sample1 and ‘&’ for sample2.

3. We will proceed with the decleration of a Hashmap.

4. Lastly we will take a for loop which iterates over the parts of the string obtained after the seperation which is splitted into key and value and then stored in the map.

The code given below demonstrate the same.

The method used is split, it splits up the string and then stores into hash map in correct format.
// Defines a Hashmap which will be used in this sample.

Map map = new HashMap();

/** * This String text could vary this could be like “key1=value1,key2=value2,key3=value3” or could be using any * kind of seperator. The seperator used in this case is ‘,’ This could be any character but you should keep * in mind as what is it. */ String text = “A=B&C=D&E=F”;// In this case seperator is ‘&’

Map map = new HashMap();

// Seperator is specified here, to split string on this basis
for(String keyValue : text.split(” *& *”)) {

// Here the each part is futher splitted taking in account the equal sign ‘=’ which demarcates the key // and valuefor the hashmap

String[] pairs = keyValue.split(” *= *”, 2);

// Those key and values are then put into hashmap
map.put(pairs[0], pairs.length == 1 ? “” : pairs[1]);

}// Successfully String to hashmap transformation is completed

150 150 Burnignorance | Where Minds Meet And Sparks Fly!