[英]Converting the type of a generic Collection in Java
在我的代码中的几个地方,我有ArrayLists和TreeSets我希望转换其通用类型。 因此,例如,我有一个ArrayList<Integer>
,我希望将其转换为ArrayList<Long>
。 或者我有一个TreeSet<BigInteger>
,我希望将其转换为TreeSet<String>
。
可以进行所有这些转换,但是随后我必须为每种类型转换创建一个不同的函数。 因此,我想创建一个通用函数,其签名如下所示:
public static <Q,T> Collection<Q> convert(Collection<T> col, Class<Q> Q)
我想要的是从col
(例如ArrayList
)获取类,创建该类和Q
类型的新集合(称为newCol
),然后遍历col
并将每个T
类型的元素转换为Q
类型并添加它到newCol
,最后返回newCol
。
我怎样才能做到这一点?
没有像Java中强制转换不兼容类这样的特殊机制。 您需要指定一个显式函数来执行转换。 使用Java 8确实很容易:
public static <Q,T,C extends Collection<Q>> C convert(Collection<T> col, Function<T, Q> fn,
Supplier<C> supplier) {
return col.stream().map(fn).collect(Collectors.toCollection(supplier));
}
像这样使用它:
TreeSet<BigInteger> values = // fill them somehow
TreeSet<String> converted = convert(values, BigInteger::toString, TreeSet::new);
@Tagir Valeev是正确的。 您可以在Java 8中轻松完成此操作。但是,如果您使用Java 7,则可以尝试执行以下操作:
public static <F, T> Collection<T> transform(Collection<F> fromCollection, Function<? super F, T> function) {
return new TransformedCollection<F, T>(fromCollection, function);
}
static class TransformedCollection<F, T> extends AbstractCollection<T> {
final Collection<F> fromCollection;
final Function<? super F, ? extends T> function;
TransformedCollection(Collection<F> fromCollection, Function<? super F, ? extends T> function) {
this.fromCollection = checkNotNull(fromCollection);
this.function = checkNotNull(function);
}
@Override public void clear() {
fromCollection.clear();
}
@Override public boolean isEmpty() {
return fromCollection.isEmpty();
}
@Override public Iterator<T> iterator() {
return Iterators.transform(fromCollection.iterator(), function);
}
@Override public int size() {
return fromCollection.size();
}
}
它是Guava库中的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.