[英]java method to convert List<String> to List<T> where T can be Integer or Long
Given a List<String>
, how to write a method to convert to it to List<T>
where T can be Integer
or Long
but this is available at runtime only.给定
List<String>
,如何编写将其转换为List<T>
的方法,其中 T 可以是Integer
或Long
,但这仅在运行时可用。 Here is the code that I could come up with.这是我能想出的代码。 It seems to work.
它似乎工作。
Is this the right way to do it?这是正确的方法吗?
Can it be simplified further?可以进一步简化吗?
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 <T> List<T> convertCSVStringToList(String s, Class<T> type) {
return Stream.of(s.split(","))
.map(String::trim)
.map(e -> valueOf(e, type))
.collect(Collectors.toList());
}
private static <T> T valueOf(String s, Class<T> 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 <%s> to type %s", s, type.getSimpleName()));
}
return t;
}
Rather than supplying a Class<T>
, supply a Function<String, T>
to convertCSVStringToList(more generally, it can be a Function<? super String, ? extends T>
), and remove your valueOf
method:与其提供
Class<T>
,不如提供一个Function<String, T>
来 convertCSVStringToList (更一般地说,它可以是一个Function<? super String, ? extends T>
),然后删除你的valueOf
方法:
public static <T> List<T> convertCSVStringToList(String s, Function<String, T> fn) {
Invoking this Function
in the stream chain:在 stream 链中调用此
Function
:
return Stream.of(s.split(","))
.map(String::trim)
.map(fn)
.collect(Collectors.toList());
And invoke convertCSVStringToList
like:并调用
convertCSVStringToList
像:
System.out.println(convertCSVStringToList(s, Integer::valueOf));
Instead of passing a class, which means you need to deal with each case individually in your valueOf
method, you could pass a function that transforms the String to the desired object.无需传递 class,这意味着您需要在
valueOf
方法中单独处理每种情况,您可以传递将字符串转换为所需 object 的 function。
System.out.println(convertCSVStringToList(s, Integer::valueOf));
public static <T> List<T> convertCSVStringToList(String s, Function<String, T> transformer) {
...
.map(String::trim)
.map(transformer)
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.