How to convert String into Hashmap in java

后端 未结 6 774
梦如初夏
梦如初夏 2020-12-15 04:43

How can I convert a String into a HashMap?

String value = \"{first_name = naresh, last_nam         


        
相关标签:
6条回答
  • 2020-12-15 04:54
    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
    0 讨论(0)
  • 2020-12-15 05:03

    Should Use this way to convert into map :

        String student[] = students.split("\\{|}");
        String id_name[] = student[1].split(",");
    
        Map<String,String> studentIdName = new HashMap<>();
    
        for (String std: id_name) {
            String str[] = std.split("=");
            studentIdName.put(str[0],str[1]);
      }
    
    0 讨论(0)
  • 2020-12-15 05:08

    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}}}

    0 讨论(0)
  • 2020-12-15 05:12

    This is one solution. If you want to make it more generic, you can use the 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.

    0 讨论(0)
  • 2020-12-15 05:17
    @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())));
    }
    
    0 讨论(0)
  • 2020-12-15 05:18

    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.

    0 讨论(0)
提交回复
热议问题