我想将集合拆分为较小的分区。我为此创建了以下方法:
/**
* Splits collection into smaller collections of given size
* @param c input collection
* @param partitionSize partition maximum size
* @return collection of collections
*/
private static Collection<Collection<MyClass>> splitCollection(Collection<MyClass> c, int partitionSize) {
List<Collection<MyClass>> result = new ArrayList<>();
List<MyClass> partition = new ArrayList<>();
for (MyClass o : c) {
if (partition.size() == partitionSize) {
result.add(partition);
partition = new ArrayList<>();
}
partition.add(o);
}
if (!partition.isEmpty()) {
result.add(partition);
}
return result;
}
现在我想创建一个通用(基本类型独立)函数,以便能够调用这样的东西:
List<Collection<MyClass>> result = splitCollection(myClassList, 500, MyClass.class);
List<Collection<MyClass2>> result = splitCollection(myClass2List, 500, MyClass2.class);
但是如果我不想使用多态(如果我的类型用Object替换),我该如何实现呢?
答案 0 :(得分:2)
您要做的是使用Generics
:
private static <T> Collection<Collection<T>> splitCollection(Collection<T> c, int partitionSize) {
List<Collection<T>> result = new ArrayList<>();
List<T> partition = new ArrayList<>();
for (T o : c) {
if (partition.size() == partitionSize) {
result.add(partition);
partition = new ArrayList<>();
}
partition.add(o);
}
if (!partition.isEmpty()) {
result.add(partition);
}
return result;
}
然后你可以把它称为:
Collection<Collection<Integer>> lsts = splitCollection(Arrays.asList(1,2,3,4), 2);
Collection<Collection<String>> lsts = splitCollection(Arrays.asList("1","2","3","4"), 2);