title: java method to convert List<String> to List<T> where T can be Integer or Long
body: <p>Given a <code>List&lt;String&gt;</code>, how to write a method to convert to it to <code>List&lt;T&gt;</code> where T can be <code>Integer</code> or <code>Long</code> but this is available at runtime only. Here is the code that I could come up with. It seems to work.</p>
  
  <p>Is this the right way to do it?<br>
  Can it be simplified further?</p>
  
  <pre><code>public static void main(String[] args) {
      String s = "1, 2, 3, 4";
      System.out.println(convertCSVStringToList(s, Integer.class));
      System.out.println(convertCSVStringToList(s, Long.class));
  }
  
  public static &lt;T&gt; List&lt;T&gt; convertCSVStringToList(String s, Class&lt;T&gt; type) {
      return Stream.of(s.split(","))
          .map(String::trim)
          .map(e -&gt; valueOf(e, type))
          .collect(Collectors.toList());
  }
  
  
  private static &lt;T&gt; T valueOf(String s, Class&lt;T&gt; type) {
      T t = null;
  
      try {
          if (type.equals(Integer.class)) {
              t = (T) Integer.valueOf(s);
          } else if (type.equals(Long.class)) {
              t = (T) Long.valueOf(s);
          }
      } catch (NumberFormatException e) {
          System.err.println(String.format("Cannot convert &lt;%s&gt; to type %s", s, type.getSimpleName()));
      }
  
      return t;
  }
  </code></pre>