如何在java中将String转换为Hashmap

时间:2014-10-21 11:49:03

标签: java collections hashmap

如何将字符串转换为哈希映射

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

进入

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

键是first_name,last_name,gender,值是naresh,kumar,male

注意:键可以是city = hyderabad

之类的任何内容

非常感谢任何通用方法。

6 个答案:

答案 0 :(得分:40)

这是一个解决方案。如果您想使它更通用,您可以使用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
}

例如,您可以切换

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

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

如果您使用StringUtils包中包含的apache.commons.lang

答案 1 :(得分:7)

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

让我们开始

  1. {&gt;&gt; first_name = naresh,last_name = kumar,gender = male
  2. 中删除}String
  3. String&gt;&gt;分割, 3元素数组
  4. 现在您有array 3元素
  5. 迭代array并将每个元素拆分为=
  6. 创建Map<String,String>,将每个部分分隔为=。第一部分为Key,第二部分为Value

答案 2 :(得分:0)

由于我相当宽容地使用Gson,因此我可以分享一种基于Gson的方法:

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

它的作用是:

  1. gson.toJson(value)会将您的对象序列化为其等效的Json表示形式。
  2. gson.fromJson会将Json字符串转换为指定的对象。 (在此示例中-Map

这种方法的灵活性在于,您可以将Object而不是String传递给toJson方法。

答案 3 :(得分:0)

应该使用这种方式转换为地图:

    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]);
  }

答案 4 :(得分:-1)

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

答案 5 :(得分:-1)

试试看:)

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

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