核心思想:就是计算出相对均等的桶大小,然后利用Guava的Lists.partition()方法来分区。
应用场景:请求的接口只允许一次请求1000个数据,而实际上要请求的数据超过1000,此时就可以利用次方法先分割;然后,再利用多线程和CountDownLatch工具来并发获取数据,从而提高响应速度。
好了,话不多说,请看代码:
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import java.util.List;
/**
* @author fanggang
*/
public class ListUtil {
/**
* 尽可能的等分一个List为N个List。
*
* @param sourceList 被等分的List
* @param maxPartitionCapacity 最大分片容量
* @param <T> List的元素类型
* @return 返回一个分割好的二维List
*/
public static <T> List<List<T>> splitList(List<T> sourceList, int maxPartitionCapacity) {
if (sourceList == null || sourceList.isEmpty() || maxPartitionCapacity <= 0) {
return Lists.newArrayList();
}