Suppose I need to parse space delimited lists of numbers where some lists contain integers and some lists contain doubles. What would be a good way to generalize the following functions to reduce repetition? I was thinking this might be a good use case for Generics?
public static ArrayList<Integer> stringToIntList(String str)
{
String[] strs = str.split("\\s");
ArrayList<Integer> output = new ArrayList<Integer>();
for (String val : strs)
{
output.add(Integer.parseInt(val));
}
return output;
}
public static ArrayList<Double> stringToDoubleList(String str)
{
String[] strs = str.split("\\s");
ArrayList<Double> output = new ArrayList<Double>();
for (String val : strs)
{
output.add(Double.parseDouble(val));
}
return output;
}
You can do this with generics if you have some sort of function (e.g. java.util.function.Function
or com.google.common.base.Function
) which takes a String
and returns the desired type.
static <T> ArrayList<T> stringToList(
String str, Function<? super String, ? extends T> fn) {
String[] strs = str.split("\\s");
ArrayList<T> output = new ArrayList<>();
for (String val : strs)
{
output.add(fn.apply(val));
}
return output;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With