How to convert String into Hashmap in java

convert string to hashmap javascript
convert json string to map in java
convert string to map in java 8
split string into hashmap java
hashmap string to map
split string and store in map java
convert json array to map in java
nested json to hashmap java

How can I convert a String into a HashMap?

String value = "{first_name = naresh, last_name = kumar, gender = male}"

into

Map<Object, Object> = {
    first_name = naresh,
    last_name = kumar,
    gender = male
}

Where the keys are first_name, last_name and gender and the values are naresh, kumar, male.

Note: Keys can be any thing like city = hyderabad.

I am looking for a generic approach.

This is one solution. If you want to make it more generic, you can us StringUtils library.

String value = "{first_name = naresh,last_name = kumar,gender = male}";
value = value.substring(1, value.length()-1);           //remove curly brackets
String[] keyValuePairs = value.split(",");              //split the string to creat key-value pairs
Map<String,String> map = new HashMap<>();               

for(String pair : keyValuePairs)                        //iterate over the pairs
{
    String[] entry = pair.split("=");                   //split the pairs to get key and value 
    map.put(entry[0].trim(), entry[1].trim());          //add them to the hashmap and trim whitespaces
}

For example you can switch

 value = value.substring(1, value.length()-1);

to

 value = StringUtils.substringBetween(value, "{", "}");

if you are using StringUtils which is contained in apache.commons.lang package.

How to convert String into Hashmap in java, Test; import java.util.Map; import split String by " ", then split each item by "=" and put pairs into map. private HashMap<String, String> convert(String str) { String[] tokens = str.split("&"); HashMap<String, String> map = new  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<String, String> map = new HashMap<String, String>(); /** * This String text could vary this could be like “key1=value1,key2=value2,key3=value3” or could be using any * kind of seperator.

String value = "{first_name = naresh,last_name = kumar,gender = male}"

Let's start

  1. Remove { and } from the String>>first_name = naresh,last_name = kumar,gender = male
  2. Split the String from ,>> array of 3 element
  3. Now you have an array with 3 element
  4. Iterate the array and split each element by =
  5. Create a Map<String,String> put each part separated by =. first part as Key and second part as Value

Convert string representing key-value pairs to Map, 1) Split entry pairs and convert string array to List<String> in order to use java.​lang.Collection.Stream API from Java 1.8. Arrays.asList(str.split(",")). i converted HashMap into an String using toString() method and pass to the another method that take an String and convert this String into HashMap object. This is a very, very bad way to pass around a HashMap. It can theoretically work, but there's just way too much that can go wrong (and it will perform very badly).

Since I use Gson quite liberally, I can share a Gson based approach:

Map<Object,Object> attributes = gson.fromJson(gson.toJson(value)),Map.class);

What it does is:

  1. gson.toJson(value) will serialize your object into its equivalent Json representation.
  2. gson.fromJson will convert the Json string to specified object. (in this example - Map)

The flexibility with this approach is that you can pass an Object instead of String to toJson method.

String to HashMap JAVA, BurnIgnorance.com is a collection of tips and knowledge in tech and programming topics ranging from ASP.NET to Java, from iOS to Android, from Python to  Map<String, Object> retMap = new HashMap<String, Object> (); I want to store all the data from the JSONObject in that HashMap. Can anyone provide code for this? I want to use the org.json library. java json dictionary. Share a link to this question. improve this question. edited Jul 2 '18 at 12:36. 32 silver badges. 66 bronze badges.

@Test
public void testToStringToMap() {
    Map<String,String> expected = new HashMap<>();
    expected.put("first_name", "naresh");
    expected.put("last_name", "kumar");
    expected.put("gender", "male");
    String mapString = expected.toString();
    Map<String, String> actual = Arrays.stream(mapString.replace("{", "").replace("}", "").split(","))
            .map(arrayData-> arrayData.split("="))
            .collect(Collectors.toMap(d-> ((String)d[0]).trim(), d-> (String)d[1]));

    expected.entrySet().stream().forEach(e->assertTrue(actual.get(e.getKey()).equals(e.getValue())));
}

How To Convert String Into Hashmap, Learn how to convert a Map to a String and the other way around using both core Map<Integer, String> wordsByKey = new HashMap<>();. Blog Java and J2EE Tutorials How to convert HashMap to ArrayList in Java? Here is a simple example on how to convert HashMap to ArrayList in Java. Share & leave us some comments on what you think about this topic or if you like to add something.

try this out :)

public static HashMap HashMapFrom(String s){
    HashMap base = new HashMap(); //result
    int dismiss = 0; //dismiss tracker
    StringBuilder tmpVal = new StringBuilder(); //each val holder
    StringBuilder tmpKey = new StringBuilder(); //each key holder

    for (String next:s.split("")){ //each of vale
        if(dismiss==0){ //if not writing value
            if (next.equals("=")) //start writing value
                dismiss=1; //update tracker
            else
                tmpKey.append(next); //writing key
        } else {
            if (next.equals("{")) //if it's value so need to dismiss
                dismiss++;
            else if (next.equals("}")) //value closed so need to focus
                dismiss--;
            else if (next.equals(",") //declaration ends
                    && dismiss==1) {
                //by the way you have to create something to correct the type
                Object ObjVal = object.valueOf(tmpVal.toString()); //correct the type of object
                base.put(tmpKey.toString(),ObjVal);//declaring
                tmpKey = new StringBuilder();
                tmpVal = new StringBuilder();
                dismiss--;
                continue; //next :)
            }
            tmpVal.append(next); //writing value
        }
    }
    Object objVal = object.valueOf(tmpVal.toString()); //same as here
    base.put(tmpKey.toString(), objVal); //leftovers
    return base;
}

examples input : "a=0,b={a=1},c={ew={qw=2}},0=a" output : {0=a,a=0,b={a=1},c={ew={qw=2}}}

Map to String Conversion in Java, readValue(json, Map.class) to convert a JSON string to a Map ObjectMapper; import java.io. HashMap; import java.util. convert Java Map to / from JSONJackson Tree Model example Read JSON into Tree, like DOM […]. hashMap.keySet().toArray(); // returns an array of keys hashMap.values().toArray(); // returns an array of values. Should be noted that the ordering of both arrays may not be the same, See oxbow_lakes answer for a better approach for iteration when the pair key/values are needed. improve this answer. edited May 31 '12 at 14:17.

Jackson – Convert JSON string to Map – Mkyong.com, here i have to split this whole String "a" into broken tokens like a=100 I dont know how to add this string array here b[] to HashMap so that i  In this tutorial, you will learn about how to convert a Stream to a HashMap in Java 8. If you would like to learn more about Java Stream operations.Please check out this link . In order, to convert a stream to a collection we have to use Collectors api provided in Java 8.

Convert String to Map (Java in General forum at Coderanch), ArrayList provides the dynamic arrays in Java. Converting the HashMap key-​value pairs into an ArrayList. HashMap<String,String> countryCapitalMap= 13. Please help me how to convert to HashMap. Does Product have a unique property (ies)? – SimonC Oct 17 '11 at 4:59. The general methodology would be to iterate through the ArrayList, and insert the values into the HashMap. An example is as follows: using your comment about productCode (and assuming product code is a String) as reference

How to convert a HashMap to an ArrayList, Map<Integer, String> map = new HashMap<>(); toMap() to convert it into a Map​. Get the List to be converted into Map; Convert the List into stream using  Use the standard Collections operations. [code]ArrayList <K> keys = new ArrayList<>(); Collections.addAll(keys, map.keySet().toArray(keys)); [/code]This has the benefit of being a checked operation with generic typing at runtime.

Comments
  • Extract the "key, value" pairs from the String and create the map.
  • Did you try anything ?
  • questions related to logic description are highly discouraged as there can be multiple solutions for the above and its far off topic. by the way what was your approach did you try something or get stuck somewhere then we can help
  • This works when I know what key is exactly and how many keys are there,but if I have like 10 keys in String.
  • I tried convert the same using mapper.readValue(input,new TypeReference<Map<Object, Object>>() {}) from jackson library but raised ParseException
  • Provide answer in full is kill the OP's chance of learning. This is not helping him but encourage OP to ask same kind of question again.
  • Sorry for that, but my intention here was,if I dont know what are keys in string.
  • You dont have to know the keys. My code always uses the left side of the equal sign as the key. Did you tried it?
  • It would break if there is any comma in the key or value. Should consider that as well.
  • value = StringUtils.substringBetween(value, "{", "}"); Should not be used when value is a json string
  • Maybe trim the String to not get confused when calling map.get(trimmedString)
  • @Nareshkumar There is no issue with that.