Java util.List如何实现列表分段处理
java.util.List 分段
使用google的guava类库对List分段处理
List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);List<List<Integer>> subSets = Lists.partition(intList, 3);List<Integer> last = subSets.get(2);
原理是内部封装着我们要分段的List的引用,在subSets.get(index) 语句时,对参数List.subList()动态处理
对集合的处理
Collection<Integer> intCollection = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);Iterable<List<Integer>> subSets = Iterables.partition(intCollection, 3);List<Integer> firstPartition = subSets.iterator().next();
使用iterable进行遍历,iterator.next()方法,内部是使用固定size大小的数组循环状态size次数据,然后返回数据
使用apache common工具的的List分段处理方法
ArrayList<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);List<List<Integer>> subSets2 = ListUtils.partition(intList, 3);
这个方法和guava包的列表分段方法原理是相同的
自定义泛型方法进行分页
/** * 列表数据分组 * @param source 源数据 * @param size 根据大小分组 * @param <T> 泛型 * @return */ public static <T> List<List<T>> averageAssign(List<T> source, int size){ List<List<T>> result = new ArrayList<>(); int offset=0; boolean isZero = source.size()%size==0; int totalPage = source.size()/size + 1; int totalSize = source.size(); while(totalPage-1>=offset){ List<T> subList = null; if(offset == totalPage-1){if(isZero){ break;}//最后一段的处理subList = source.subList(size * offset, totalSize); }else{subList = source.subList(size * offset, size * (offset + 1)); } offset++; result.add(subList); } return result; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好吧啦网。
相关文章:
1. JSF中用户登出返回登录页面问题2. php中检查email完整性3. JavaScript ECMA-262-3 深入解析(二):变量对象实例详解4. ASP.NET MVC使用typeahead.js实现输入智能提示功能5. JavaScript中break、continue和return的用法区别实例分析6. Spring Web Flow 1.0 发布7. 分析Java中为什么String不可变8. Vue elementui字体图标显示问题解决方案9. 简单的理解java集合中的HashSet和HashTree几个重写方法10. 使用IDEA编写jsp时EL表达式不起作用的问题及解决方法

网公网安备