Skip to content

Instantly share code, notes, and snippets.

@mallipeddi
Created April 26, 2010 08:00
Show Gist options
  • Select an option

  • Save mallipeddi/379090 to your computer and use it in GitHub Desktop.

Select an option

Save mallipeddi/379090 to your computer and use it in GitHub Desktop.
public class Parser {
public static <T> Map<String, T> getMapFromKeyValuePairs(String str, Convertor<T> convertor) {
Map<String, T> map = new HashMap<String, T>();
String[] symbols = str.split(",");
if (symbols.length > 0) {
for (String symbol : symbols) {
String[] tuple = symbol.split(":");
if (tuple.length == 2) {
try {
T value = convertor.valueOf(tuple[1]);
map.put(tuple[0], value);
} catch (Exception e) {
System.err.println("Invalid value: " + tuple[1] + " for symbol: " + tuple[0]);
}
} else {
System.err.println("Error parsing symbol tuple: " + symbol);
}
}
}
return (map.isEmpty() ? null : map);
}
public interface Convertor<V> {
V valueOf(String s);
}
public static final Convertor<Long> LONG_CONVERTOR = new Convertor<Long>() {
public Long valueOf(String s) {
return Long.parseLong(s);
}
};
public static final Convertor<Boolean> BOOLEAN_CONVERTOR = new Convertor<Boolean>() {
public Boolean valueOf(String s) {
return ((s!= null) && (s.equalsIgnoreCase("true") || s.equalsIgnoreCase("yes")));
}
};
}
// Usage
Map<String, Boolean> map = Parser.getMapFromKeyValuePairs("IBM:true,MSFT:false", Parser.BOOLEAN_CONVERTOR);
Map<String, Long> map2 = Parser.getMapFromKeyValuePairs("IBM:1000,MSFT:500", Parser.LONG_CONVERTOR);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment