在某些场景中,需要批量执行数据,可以通过数据库分页查询,也可以通过java来对集合进行分页。将list(或其他集合)拆分成多份,java传统的集合操作中并没有这样的方法。常见方法有:
1、手动分片:
public static List> averageAssign(List source, int n) {
List> result = new ArrayList>();
int remaider = source.size() % n; //(先计算出余数)
int number = source.size() / n; //然后是商
int offset = 0;//偏移量
for (int i = 0; i < n; i++) {
List 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;
}
2、google guava分片:
import com.google.common.collect.Lists;
public class ListsPartitionTest1 {
public static void main(String[] args) {
List ls = Arrays.asList("1,2,3,4,5,6,7,8,9,1,2,4,5,6,7,7,6,6,6,6,6,66".split(","));
System.out.println(Lists.partition(ls, 20));
}
}
再如:
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.List;
public class ListsTest {
public static void main(String[] args) {
List list = Arrays.asList(1, 2, 3, 4, 5);
// 按大小 2 拆分
List> listPartitionList = Lists.partition(list, 2);
System.out.println("原 List:");
System.out.println(list);
System.out.println("拆分后:");
for (List partition: listPartitionList) {
System.out.println(partition);
}
}
}
原 List:
[1, 2, 3, 4, 5]
拆分后:
[1, 2]
[3, 4]
[5]
3、apache commons collections分片:
import org.apache.commons.collections4.ListUtils;
public class ListsPartitionTest2 {
public static void main(String[] args) {
List intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
System.out.println(ListUtils.partition(intList, 3));
}
}
4、使用Java8 stream流 partition by,partitioningBy是一种特殊的分组,只会分成两组
Listnums = Lists.newArrayList(1,1,8,2,3,4,5,6,7,9,10); Map > numMap= numList.stream().collect(Collectors.partitioningBy(num -> num > 5)); System.out.println(numMap); {false=[2, 3, 4, 5], true=[8, 6, 7, 9, 10]}



