Here you can find the source of splitIntoSubListsByNumber(final List
public static <T> List<List<T>> splitIntoSubListsByNumber(final List<T> list, final int numberOfSublists)
//package com.java2s; /*-//w w w . j ava 2 s .c o m * ============================LICENSE_START============================ * data.messie (core) * ===================================================================== * Copyright (C) 2013 - 2017 Dr. Raphael Romeikat * ===================================================================== * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/gpl-3.0.html>. * =============================LICENSE_END============================= */ import java.util.ArrayList; import java.util.List; public class Main { public static <T> List<List<T>> splitIntoSubListsByNumber(final List<T> list, final int numberOfSublists) { final int sizeOfSublists = (int) Math.ceil((double) list.size() / (double) numberOfSublists); return splitIntoSubListsBySize(list, sizeOfSublists); } public static <T> List<List<T>> splitIntoSubListsBySize(final List<T> list, final int sizeOfSublists) { final List<List<T>> subLists = new ArrayList<List<T>>(); // Only one sublist if (sizeOfSublists < 1) { subLists.add(list); return subLists; } // Divide for (int i = 0;; i++) { final int fromIndex = i * sizeOfSublists; int toIndex = (i + 1) * sizeOfSublists; final boolean lastSublist = list.size() <= toIndex; if (lastSublist) { toIndex = list.size(); } final List<T> subList = new ArrayList<T>(list.subList(fromIndex, toIndex)); subLists.add(subList); // No more sublists to go if (lastSublist) { break; } } // Done return subLists; } }