java - Build a List<T> from a String -
i trying make generic function builds list of type based on string holds values of type delimited let's comma. have done this:
public static <t> list<t> stringtolist(string liststr, class<t> itemtype) { return arrays.aslist(liststr.split(",")).stream().map(x -> itemtype.cast(x.replaceall("\\s+|\"|\t","")))).collect(collectors.tolist()); } when try test with:
string liststringsstr = "\"foo\", \"bar\""; list<string> ress = stringtolist(liststringsstr, string.class); string listintegersstr = "1,10,-1,0"; list<integer> resi = stringtolist(liststringsstr, integer.class); i have 2 problems.
- in first case (string) double quote around each string item: ""foo"", ""bar"".
- in second case (integer)
java.lang.classcastexception: cannot cast java.lang.string java.lang.integermeans can't convert "1" 1. know worksinteger::parseint, want make generic method.
any ideas?
[edit] - because caused confusion way posted it, add test code:
string liststringsstr = "\"foo\", \"bar\""; list<string> liststrings = arrays.aslist("foo", "bar"); string listintegersstr = "1,10,-1,0"; list<integer> listintegers = arrays.aslist(1, 10, -1, 0); list<string> ress = stringtolist(liststringsstr, string.class); system.out.println(ress); system.out.println(liststrings); assert (ress.containsall(liststrings)); list<integer> resi = stringtolist(listintegersstr, integer.class); system.out.println(resi); system.out.println(listintegers); assert (resi.containsall(listintegers)); after including x.replaceall("\\s+|\"|\t","") first assertion pass, second fails. console output is
[foo, bar] [foo, bar] [1, 10, -1, 0] [1, 10, -1, 0] listintegers holds integer suppose resi holds ints, or broke java's type safety :d
for problem #2: simple modification pass function<string, t> instead of class<t>. function define how parse string class of desired type. possible values:
function<string, string> stringparser = s -> s; function<string, integer> intparser = s -> integer.parseint(s); for problem #1: in example gave input strings do contain quotes. have made input string "foo,bar" avoid having quotes in output. if don't have control on input, can trim quotes/whitespace/etc. part of parsing function, or separate words more advanced splitting commas - input csv file?
Comments
Post a Comment