[英]How do I create any Collection given the collection name(ArrayList, LinkedList etc) and items in the collection?
我正在尝试创建一个接受集合类型和集合内项目类型的方法。
ArrayList<Integer> ints = getCollection(ArrayList.class, Integer.class);
如何编写getCollection以便在给定任何 Collection 子类和任何 Number 子类的情况下,该方法应该创建一个集合并用 Number 的随机元素或 Number 的子类型填充它?
如果可以的话,最好为集合传入一个 Supplier ,并传入一个 Function 以从 Number 转换为子类型,例如:
private static final SecureRandom RND = new SecureRandom();
private static final int COUNT_MAX = 100;
public static void main(String[] args) {
ArrayList<Integer> ints = getCollection(ArrayList::new, Number::intValue);
System.out.println(ints);
Set<Double> doubles = getCollection(HashSet::new, Number::doubleValue);
System.out.println(doubles);
}
private static <T extends Collection<U>, U extends Number> T getCollection(
Supplier<T> supplier, Function<Number, U> fn) {
T collection = supplier.get();
int count = RND.nextInt(COUNT_MAX);
for (int i = 0; i < count; i++)
collection.add(fn.apply(RND.nextInt()));
return collection;
}
这样,您将不需要任何铸造。
使用流更新:
private static <T extends Collection<U>, U extends Number> T getCollection(
Supplier<T> supplier, Function<Number, U> fn) {
int count = RND.nextInt(COUNT_MAX);
return RND.ints().limit(count).boxed().map(fn)
.collect(Collectors.toCollection(supplier));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.