Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Using Generics for String Parsing to Improve DRYness

Tags:

java

generics

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;
}
like image 400
evan.oman Avatar asked Mar 12 '23 18:03

evan.oman


1 Answers

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;
 }
like image 82
Andy Turner Avatar answered Mar 24 '23 02:03

Andy Turner