How to split a list into n equal parts

Suppose you want to split a into sub list of approximately equal size with specify parts.

public class CollectionUtils {

public static <T> List<List<T>> split(List<T> list, int numberOfParts) {
      List<List<T>> numberOfPartss = new ArrayList<>(numberOfParts);
      int size = list.size();
      int sizePernumberOfParts = (int) Math.ceil(((double) size) / numberOfParts);
      int leftElements = size;
      int i = 0;
      while (i < size && numberOfParts != 0) {
          numberOfPartss.add(list.subList(i, i + sizePernumberOfParts));
          i = i + sizePernumberOfParts;
          leftElements = leftElements - sizePernumberOfParts;
          sizePernumberOfParts = (int) Math.ceil(((double) leftElements) / --numberOfParts);
       }
       return numberOfPartss;
   }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s