2010-10-25 14 views
6

Czy istnieje jakaś wspólna funkcja (w apache commons lub podobnym) do tworzenia map z łańcuchów podobnych do parametrów zapytania?wspólna funkcja java do tworzenia map z łańcuchów

do konkretnych:

Variant a (kwerendy)

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

Wariant B (Cachecontrol-Header)

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

Nie chcę wyważać otwartych drzwi.

Dzięki

Odpowiedz

1

Wydaje się, że to proste rozszerzenie HashMap byłoby to zrobić:

/** 
* 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()); 

    } 
} 
1

Nie sądzę taka biblioteka istnieje, ale jeśli chcesz reimplement go z niewielu kodu, można użyć „lambda zorientowanych biblioteki”, takie jak Guava lub LambdaJ.

2

stringtomap

Wypróbuj lub przeglądać kod źródłowy, aby zobaczyć, jak to zostało zrealizowane.

Powiązane problemy