I am trying to make a generic function that builds a List of any type based on a string that holds values of that type delimited by let's say a comma. I 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 I try to test it 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 two problems.
- In the first case (String) I get an extra double quote around each string item: ""Foo"", ""Bar"".
- In the second case (Integer) I get a
java.lang.ClassCastException: Cannot cast java.lang.String to java.lang.Integer
which means that it can't convert "1" to 1. I know this works withInteger::parseInt
, but I want to make a generic method.
Any Ideas?
[EDIT] - Because I caused confusion the way I posted it, I add the 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 the x.replaceAll("\\s+|\"|\t","")
the first assertion now pass, the second fails. The console output is
[Foo, Bar]
[Foo, Bar]
[1, 10, -1, 0]
[1, 10, -1, 0]
listIntegers holds Integer thus I suppose resI holds ints, or I just broke java's type safety :D