String to HashMap JAVA

后端 未结 10 1237
我寻月下人不归
我寻月下人不归 2020-12-02 11:32

I have a Java Property file and there is a KEY as ORDER. So I retrieve the VALUE of that KEY using the getProperty(

相关标签:
10条回答
  • 2020-12-02 11:53

    You can also use JSONObject class from json.org to this will convert your HashMap to JSON string which is well formatted

    Example:

    Map<String,Object> map = new HashMap<>();
    map.put("myNumber", 100);
    map.put("myString", "String");
    
    JSONObject json= new JSONObject(map);
    
    String result= json.toString();
    
    System.out.print(result);
    

    result:

    {'myNumber':100, 'myString':'String'}
    

    Your can also get key from it like

    System.out.print(json.get("myNumber"));
    

    result:

    100
    
    0 讨论(0)
  • 2020-12-02 11:58

    Assuming no key contains either ',' or ':':

    Map<String, Integer> map = new HashMap<String, Integer>();
    for(final String entry : s.split(",")) {
        final String[] parts = entry.split(":");
        assert(parts.length == 2) : "Invalid entry: " + entry;
        map.put(parts[0], new Integer(parts[1]));
    }
    
    0 讨论(0)
  • 2020-12-02 11:59

    Use StringTokenizer to parse the string.

    String s ="SALES:0,SALE_PRODUCTS:1,EXPENSES:2,EXPENSES_ITEMS:3";
        Map<String, Integer> lMap=new HashMap<String, Integer>();
    
    
        StringTokenizer st=new StringTokenizer(s, ",");
        while(st.hasMoreTokens())
        {
            String [] array=st.nextToken().split(":");
            lMap.put(array[0], Integer.valueOf(array[1]));
        }
    
    0 讨论(0)
  • 2020-12-02 12:00

    Use the String.split() method with the , separator to get the list of pairs. Iterate the pairs and use split() again with the : separator to get the key and value for each pair.

    Map<String, Integer> myMap = new HashMap<String, Integer>();
    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], Integer.valueOf(keyValue[1]));
    }
    
    0 讨论(0)
  • 2020-12-02 12:03

    You can do that with Guava's Splitter.MapSplitter:

    Map<String, String> properties = Splitter.on(",").withKeyValueSeparator(":").split(inputString);
    
    0 讨论(0)
  • 2020-12-02 12:03

    You can to use split to do it:

     String[] elements = s.split(",");
     for(String s1: elements) {
         String[] keyValue = s1.split(":");
         myMap.put(keyValue[0], keyValue[1]);
     }
    

    Nevertheless, myself I will go for guava based solution. https://stackoverflow.com/a/10514513/1356883

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