Guava中Lists.partition(List, size) 方法
Lists.partition 可以进行集合的拆分,Lists 需要引入的包 import com.google.common.collect.Lists;
可通过 添加依赖获取:
implementation 'com.google.guava:guava:31.1-android'
添加依赖后,编译可能会遇到一些问题,比如:
Variant 'sourcesElements' capability org.checkerframework:checker-qual:3.12.0
为了避免引入新的问题,可以点击源码查看该方法(实现之后再删除改依赖),发现实现方法其实很简单,可以直接摘出来,如下是实现代码:
import java.math.RoundingMode;
import java.util.AbstractList;
import java.util.List;
import static java.lang.Math.abs;
import static java.math.RoundingMode.HALF_EVEN;
import static java.math.RoundingMode.HALF_UP;
public class ListsUtil {
public static <T extends Object> List<List<T>> partition(List<T> list, int size) {
// checkNotNull(list);
// checkArgument(size > 0);
return new Partition<>(list, size);
}
private static class Partition<T extends Object> extends AbstractList<List<T>> {
final List<T> list;
final int size;
Partition(List<T> list, int size) {
this.list = list;
this.size = size;
}
@Override
public List<T> get(int index) {
// checkElementIndex(index, size());
int start = index * size;
int end = Math.min(start + size, list.size());
return list.subList(start, end);
}
@Override
public int size() {
return divide(list.size(), size, RoundingMode.CEILING);
}
@Override
public boolean isEmpty() {
return list.isEmpty();
}
}
public static int divide(int p, int q, RoundingMode mode) {
if (q == 0) {
throw new ArithmeticException("/ by zero"); // for GWT
}
int div = p / q;
int rem = p - q * div; // equal to p % q
if (rem == 0) {
return div;
}
/*
* Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. We just have to
* deal with the cases where rounding towards 0 is wrong, which typically depends on the sign of
* p / q.
*
* signum is 1 if p and q are both nonnegative or both negative, and -1 otherwise.
*/
int signum = 1 | ((p ^ q) >> (Integer.SIZE - 1));
boolean increment;
switch (mode) {
case UNNECESSARY:
// checkRoundingUnnecessary(rem == 0);
// fall through
case DOWN:
increment = false;
break;
case UP:
increment = true;
break;
case CEILING:
increment = signum > 0;
break;
case FLOOR:
increment = signum < 0;
break;
case HALF_EVEN:
case HALF_DOWN:
case HALF_UP:
int absRem = abs(rem);
int cmpRemToHalfDivisor = absRem - (abs(q) - absRem);
// subtracting two nonnegative ints can't overflow
// cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2).
if (cmpRemToHalfDivisor == 0) { // exactly on the half mark
increment = (mode == HALF_UP || (mode == HALF_EVEN & (div & 1) != 0));
} else {
increment = cmpRemToHalfDivisor > 0; // closer to the UP value
}
break;
default:
throw new AssertionError();
}
return increment ? div + signum : div;
}
}
可代替Guava中 Lists.partition(List, size)方法;