Guava中 Lists.partition(List, size)方法提取

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  List> partition(List list, int size) {
//        checkNotNull(list);
//        checkArgument(size > 0);return  new Partition<>(list, size);}private static class Partition extends AbstractList> {final List list;final int size;Partition(List list, int size) {this.list = list;this.size = size;}@Overridepublic List get(int index) {
//            checkElementIndex(index, size());int start = index * size;int end = Math.min(start + size, list.size());return list.subList(start, end);}@Overridepublic int size() {return divide(list.size(), size, RoundingMode.CEILING);}@Overridepublic 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 % qif (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 throughcase 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 markincrement = (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)方法;


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部