Java List Split splitList(List source, int count)

Here you can find the source of splitList(List source, int count)

Description

This method takes a list and breaks it into count lists backed by the original list, with elements being equally spaced among the lists.

License

Open Source License

Parameter

Parameter Description
T the type contained in the list
source the source list that will be used to back the <tt>count</tt> lists
count the number of lists to partition the source into.

Return

a lists of lists, each of with the same size with at most a difference of 1.

Declaration

public static <T> List<List<T>> splitList(List<T> source, int count) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**// w  w  w.  j  a  v a 2  s. c  o  m
     * This method takes a list and breaks it into <tt>count</tt> lists backed by the original 
     * list, with elements being equally spaced among the lists. The lists will be returned in
     * order of the consecutive values they represent in the source list.
     * <br><br><b>NOTE</b>: Because the implementation uses {@link List#subList(int, int) }, 
     * changes to the returned lists will be reflected in the source list. 
     * 
     * @param <T> the type contained in the list
     * @param source the source list that will be used to back the <tt>count</tt> lists
     * @param count the number of lists to partition the source into. 
     * @return a lists of lists, each of with the same size with at most a difference of 1. 
     */
    public static <T> List<List<T>> splitList(List<T> source, int count) {
        if (count <= 0)
            throw new RuntimeException("Chunks must be greater then 0, not " + count);
        List<List<T>> chunks = new ArrayList<List<T>>(count);
        int baseSize = source.size() / count;
        int remainder = source.size() % count;
        int start = 0;

        for (int i = 0; i < count; i++) {
            int end = start + baseSize;
            if (remainder-- > 0)
                end++;
            chunks.add(source.subList(start, end));
            start = end;
        }

        return chunks;
    }
}

Related

  1. splitList(List files, int limit)
  2. splitList(List list, int number)
  3. splitList(List _list, int _elements)
  4. splitList(List list, int page)
  5. splitList(List parent, int subSize)
  6. splitList(List sourceList, int spliTotal)
  7. splitListIntoParts(List list, int sizeOfEachPart)