java中如何将String转换为Hashmap

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26485964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:37:08  来源:igfitidea点击:

How to convert String into Hashmap in java

javacollectionshashmap

提问by Naresh kumar

How can I convert a Stringinto a HashMap?

如何将 a 转换String为 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_nameand genderand the values are naresh, kumar, male.

其中键是first_name,last_namegender值是naresh, kumar, male

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

注意:键可以是任何类似city = hyderabad.

I am looking for a generic approach.

我正在寻找一种通用的方法。

采纳答案by kai

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

这是一种解决方案。如果你想让它更通用,你可以使用我们的StringUtils库。

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 StringUtilswhich is contained in apache.commons.langpackage.

如果您正在使用包中StringUtils包含的内容apache.commons.lang

回答by Ruchira Gayan Ranaweera

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 Stringfrom ,>> array of 3 element
  3. Now you have an arraywith 3element
  4. Iterate the arrayand split each element by =
  5. Create a Map<String,String>put each part separated by =. first part as Keyand second part as Value
  1. 从>>first_name = naresh,last_name = kumar,gender = male 中删除{and}String
  2. 拆分Stringfrom ,>> 3 个元素的数组
  3. 现在你有一个arraywith3元素
  4. 迭代array并拆分每个元素=
  5. 创建一个Map<String,String>put 每个部分由=. 第一部分作为Key和第二部分作为Value

回答by Hiren

@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())));
}

回答by suliman alobody

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

示例输入:“a=0,b={a=1},c={ew={qw=2}},0=a”输出:{0=a,a=0,b={a=1} ,c={ew={qw=2}}}

回答by tryingToLearn

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

由于我非常自由地使用Gson,我可以分享一个基于 Gson 的方法:

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.fromJsonwill convert the Json string to specified object. (in this example - Map)
  1. gson.toJson(value)将您的对象序列化为其等效的 Json 表示形式。
  2. gson.fromJson将 Json 字符串转换为指定的对象。(在这个例子中 - Map

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

这种方法的灵活性在于您可以将对象而不是字符串传递给 toJson方法。