给定 List<String>
,如何编写一个方法将其转换为 List<T>
其中 T 可以是 Integer
或Long
但这仅在运行时可用。这是我能想到的代码。看来有效。
这是正确的方法吗?
可以进一步简化吗?
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;
}
最佳答案
而不是提供 Class<T>
,供应Function<String, T>
转换CSVStringToList(更一般地说,它可以是 Function<? super String, ? extends T>
),并删除您的 valueOf
方法:
public static <T> List<T> convertCSVStringToList(String s, Function<String, T> fn) {
调用此 Function
在流链中:
return Stream.of(s.split(","))
.map(String::trim)
.map(fn)
.collect(Collectors.toList());
并调用convertCSVStringToList
像:
System.out.println(convertCSVStringToList(s, Integer::valueOf));
关于java 将 List<String> 转换为 List<T> 的方法,其中 T 可以是 Integer 或 Long,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61456745/