【问题标题】:How to convert String to HashMap in Java如何在 Java 中将 String 转换为 HashMap
【发布时间】:2014-09-27 17:59:45
【问题描述】:

我是 Java 新手。我想将字符串转换为HashMap。但我不知道如何转换它。下面是我的代码。

public class Excer5sam {     
    public static void main(String[] args) throws IOException{    
        BufferedReader fl=new BufferedReader(new FileReader("/home/mansoor/Documents/Fileip.txt"));

        Map<String, String>map=new HashMap<String, String>();   
        List<String>str=new ArrayList<>();   
        String ln=null;  
        while((ln=fl.readLine())!=null){  
            str.add(ln);   
            }   
        fl.close();  
        String s="";   
        for(String s1:str){   
            s+=s1+",";   
            }   
        System.out.println("value of s:"+s);   
        String v=s.replace(",", " ");  
        System.out.println("v value:"+"  "+v);  
        }  
}

我的意见:

“u1”,“u10”  
“u2”,“u41”  
“u3”,“u10”  
“u4”,“u81”  
“u5”,“u10”  
“u6”,“u10”  
“u7”,“u31”  
“u8”,“u11”  

我的字符串输出(“v值”):

“u1”“u10”“u2”“u41”“u3”“u10”“u4”“u81”“u5”“u10”“u6”“u10” “u7” “u31” “u8” “u11”

我需要将此string(v Value) 转换为HashMap&lt;string,String>(如键、值对)。怎么做?
谁能帮忙解决一下?

【问题讨论】:

    标签: java string hashmap


    【解决方案1】:
         HashMap<String, String> myMap = new HashMap<String, String>();
    
    
             String s = "SALES:0,SALE_PRODUCTS:1,EXPENSES:2,EXPENSES_ITEMS:3";
             String[] pairs = s.split(",");
             for (int i=0;i<pairs.length;i++) {
                 String pair = pairs[i];
                 String[] keyValue = pair.split(":");
                 myMap.put(keyValue[0], (keyValue[1]));
             }
    

    【讨论】:

    • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
    【解决方案2】:

    试试这个

    private static Map<String, String> splitToMap(String in) {
         String value = StringUtils.substringBetween(in, "{", "}"); //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 pais
         {
             String[] entry = pair.split(":");                   //split the pairs to get key and value 
             map.put(entry[0].trim().replaceAll( "[\"]", ""), entry[1].trim().replaceAll( "[\"]", ""));          //add them to the hashmap
         }
            return map;
        }
    

    【讨论】:

      【解决方案3】:

      添加 map.put(s,v);在 for 循环中你打印 s,v;

      for(String s1:str){   
                  s+=s1+",";   
                  }   
              System.out.println("value of s:"+s);   
              String v=s.replace(",", " ");  
              System.out.println("v value:"+"  "+v);
              map.put(s,v); 
              }
      

      【讨论】:

        【解决方案4】:

        试试这条线,它会对你有用

         Map<String,String> lists=new HashMap<String,String>();
          int i=1;
         for(String s1:str){   
               lists.put(String.valueof(i),s1);
             i++;
                }  
        

        您可以从索引轻松访问。

        【讨论】:

          【解决方案5】:

          在“,”上拆分你的行,并将键和值添加到地图中:

          public static void main(String[] args) throws IOException{    
              BufferedReader fl=new BufferedReader(new FileReader("T:/temp/Fileip.txt"));
          
              Map<String, String>map=new HashMap<String, String>();   
              List<String>str=new ArrayList<String>();   
              String ln=null;  
              while((ln=fl.readLine())!=null){  
                  String[] temp = ln.split(",");
                  map.put(temp[0], temp[1]);
                  }   
              fl.close();  
              }  
          

          【讨论】:

          • 如果字符串中有逗号,如“name : Name, MidName”,那么就会有问题。
          【解决方案6】:

          在读取时将值放入 M​​ap 而不是将其存储在 String 变量中。

          试试这个方法:

          while((ln=fl.readLine())!=null){  
              String[] pair = ln.split(" ");
              map.put(pair[0],pair[1]);
          } 
          

          【讨论】:

          • 非常感谢。它的工作。如果我打印地图,它会产生以下输出,地图:{“u8”=“u11”,“u7”=“u31”,“u1”=“u10”,“u4”=“u81”,“u3”= “u10”,“u5”=“u10”,“u6”=“u10”,“u2”=“u41”}。但是,如果我使用 map.containsValue("u10") 来检查所有键和值,它会打印“FALSE”作为输出。我不能再使用这张地图了。你能帮我解决这个问题吗?
          • 您确定,您的地图将所有这些值存储在键值对中吗?
          • 在更改 split(",") 和输入格式(如 'u1'='u10')后,它现在可以正常工作了。非常感谢..
          猜你喜欢
          • 2019-02-03
          • 1970-01-01
          • 1970-01-01
          • 2010-11-08
          • 1970-01-01
          • 1970-01-01
          • 2014-07-20
          • 2016-06-27
          • 1970-01-01
          相关资源
          最近更新 更多