工作中遇到将一个List划分为等长的多个List,自己写了两个方法,测试可以用,作为这个平台的第一篇博文,记录一下
-
给定子List的长度,将一个List划分为多个List
private <T> List<List<T>> averageAssign(List<T> source,int bccSize){
List<List<T>> result = Lists.newArrayList();
for (int i = 0; i < source.size() ; i = i + bccSize ) {
int offset = source.size() - i < bccSize ? source.size() : i + bccSize;
List<T> tmpList = source.subList(i, offset);
result.add(tmpList);
}
return result;
}
-
给定划分的List数目,将一个List划分为多个List
public <T> List<List<T>> averageAssign(List<T> source,int n){
List<List<T>> result=new ArrayList<List<T>>();
int remaider=source.size()%n; //(先计算出余数)
int number=source.size()/n; //然后是商
int offset=0;//偏移量
for(int i=0;i<n;i++){
List<T> value=null;
if(remaider>0){
value=source.subList(i*number+offset, (i+1)*number+offset+1);
remaider--;
offset++;
}else{
value=source.subList(i*number+offset, (i+1)*number+offset);
}
result.add(value);
}
return result;
}
-
使用Guava
@Test
public void partitionTest() {
List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7);
List<List<Integer>> partitionList = Lists.partition(list, 2);
System.out.println(partitionList);
assertEquals(4, partitionList.size());
}
值得注意的是,Lists.partition操作返回的是原list的一个视图,对原list的新增删除操作会对视图产生影响,如下:
@Test
public void partitionTest() {
// Given
List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
List<List<Integer>> subSets = Lists.partition(intList, 3);
// When
intList.add(9);
// Then
List<Integer> lastPartition = subSets.get(2);
List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8, 9);
assertThat(lastPartition, equalTo(expectedLastPartition));
}