zoukankan      html  css  js  c++  java
  • java工具类-列表分段处理

    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;
        }
  • 相关阅读:
    sparse用法matlab官方说明
    C++双向循环链表
    循环链表以及迭代器的使用c++
    顺序队列c++
    顺序栈c++
    尾插法链表
    邻接表建立图
    深度优先搜索树与广度优先搜索树
    tensorflow-笔记02
    深度学习-框架介绍
  • 原文地址:https://www.cnblogs.com/gne-hwz/p/13255489.html
Copyright © 2011-2022 走看看