核心思想:就是計算出相對均等的桶大小,然後利用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();
}
final int sourceListSize = sourceList.size();
// 之所以沒是用庫函數的方式實現,是因爲這種方式效率更高(毫秒和微秒的差別)
final int partitionCount = sourceListSize / maxPartitionCapacity +
(sourceListSize % maxPartitionCapacity > 0 ? 1 : 0);
final int partitionSize = sourceListSize / partitionCount +
(sourceListSize % partitionCount > 0 ? 1 : 0);
/*
int partitionCount = IntMath.divide(
sourceListSize, maxPartitionCapacity, RoundingMode.CEILING);
int partitionSize = IntMath.divide(
sourceListSize, partitionCount, RoundingMode.CEILING);
*/
return Lists.partition(sourceList, partitionSize);
}
}