Java: Using Generics for String Analysis to Improve Drying

Suppose I need to parse tables with limited space in which some lists contain integers and some lists contain paired ones. What would be a good way to generalize the following functions to reduce repetition? I thought this might be a useful option 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;
}
+4
source share
2 answers

You can do this with generics if you have some kind of function (like, java.util.function.Functionor com.google.common.base.Function) that takes Stringand 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;
 }
+4
source

With Java 8, this can be pretty brief:

static <T> List<T> convertToList(
        String string, Function<String, T> function) {
    return Pattern.compile("\\s").splitAsStream(string)
            .map(function).collect(Collectors.toList());
}

public static void main(String[] args) {
    String s = "3 4";
    System.out.println(convertToList(s,Double::parseDouble)); // [3.0, 4.0]
    System.out.println(convertToList(s,Integer::parseInt)); // [3, 4]
}

, .

+3

All Articles