Skip to content

Instantly share code, notes, and snippets.

@JanMalch
Last active May 20, 2018 19:37
Show Gist options
  • Save JanMalch/8bbb6391cab5b3ced6ec9c9563c0d379 to your computer and use it in GitHub Desktop.
Save JanMalch/8bbb6391cab5b3ced6ec9c9563c0d379 to your computer and use it in GitHub Desktop.
Splitting a List evenly into Sub-Lists
import com.sun.istack.internal.NotNull;
import java.util.*;
/**
* @author github.com/JanMalch
*/
public class SplitList {
/**
* Splits a List into even sub-lists. Doesn't sort the sub-lists.
* @param base The base list, that will be split up
* @param splitInto Specifies in how many the base will be split up
* @return
*/
public static <T> List<List<T>> evenly(List<T> base, int splitInto) {
return SplitList.evenly(base, splitInto, null);
}
/**
* Splits a List into even sub-lists
* @param base The base list, that will be split up
* @param splitInto Specifies in how many the base will be split up
* @param comparator The comparator to sort the list with.
* @return A list with all the sub-lists. This lists length will always be equal to splitInto.
*/
public static <T> List<List<T>> evenly(List<T> base, int splitInto, @NotNull Comparator<? super T> comparator) {
List<T> baseCopy = new ArrayList<>(base);
List<List<T>> output = new ArrayList<>(splitInto);
if (comparator != null) {
baseCopy.sort(comparator);
}
int subListSize = (int) Math.floor(baseCopy.size() / splitInto);
int over = baseCopy.size() % splitInto;
int start = 0;
int end = subListSize;
for (int i = 0; i < splitInto; i++) {
if (i < over) {
end++;
}
output.add(baseCopy.subList(start, end));
start = end;
end = start + subListSize;
}
return output;
}
}
ArrayList<Integer> original = new ArrayList<>(Arrays.asList(7, 6, 5, 1, 4));
// Splits list into 3 sub-lists
// Doesn't sort
List<List<Integer>> foo = SplitList.evenly(original, 3);
// Splits list into 2 sub-lists
// Sorts sub-lists by their natural order
List<List<Integer>> foobar = SplitList.evenly(original, 2, Comparator.naturalOrder());
// Splits list into 4 sub-lists
// Sorts sub-lists in their reverse natural order
List<List<Integer>> bar = SplitList.evenly(original, 4, Comparator.reverseOrder());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment