代码之家  ›  专栏  ›  技术社区  ›  boecko

从字符串创建映射的通用java函数

  •  6
  • boecko  · 技术社区  · 14 年前

    是否有任何公共函数(在apache commons或类似的函数中)可以从查询参数(如字符串)生成映射?

    具体到:

    变体a(查询字符串)

    s="a=1&b=3"   
    => Utils.mapFunction(s, '&', '=') 
    =>  (Hash)Map { a:1; b:3 }
    

    s="max-age=3600;must-revalidate"
    => Utils.mapFunction(s, ';', '=') 
    =>  (Hash)Map { max-age:3600; must-revalidate:true }
    

    我不想重新发明轮子。

    3 回复  |  直到 14 年前
        1
  •  1
  •   Gary    14 年前

    似乎一个简单的HashMap扩展就可以做到这一点:

    /**
     * Simple demo of extending a HashMap
     */
    public class TokenizedStringHashMap extends HashMap<String, String> {
    
      void putAll(String tokenizedString, String delimiter) {
        String[] nameValues = tokenizedString.split(delimiter);
        for (String nameValue : nameValues) {
          String[] pair = nameValue.split("=");
          if (pair.length == 1) {
            // Duplicate the key name if there is only one value
            put(pair[0], pair[0]);
          } else {
            put(pair[0], pair[1]);
          }
        }
      }
    
      public static void main(String[] args) {
        TokenizedStringHashMap example = new TokenizedStringHashMap();
    
        example.putAll("a=1&b=3", "&");
        System.out.println(example.toString());
        example.clear();
    
        example.putAll("max-age=3600;must-revalidate", ";");
        System.out.println(example.toString());
    
      }
    }
    
        2
  •  2
  •   dogbane    14 年前

    stringtomap

    尝试一下或者浏览源代码,看看它是如何实现的。

        3
  •  1
  •   Benoit Courtine    14 年前

    我不认为存在这样的库,但是如果您想用很少的代码重新实现它,可以使用“面向lambda的库”,例如 Guava LambdaJ .