Skip to content

Instantly share code, notes, and snippets.

@AnkitKiet
Created August 9, 2020 05:23
Show Gist options
  • Save AnkitKiet/6c5fd34d390062555c80eb3b0d7a4de6 to your computer and use it in GitHub Desktop.
Save AnkitKiet/6c5fd34d390062555c80eb3b0d7a4de6 to your computer and use it in GitHub Desktop.
public final class Partition<T> extends AbstractList<List<T>> {
private final List<T> list;
private final int chunkSize;
public Partition(List<T> list, int chunkSize) {
this.list = new ArrayList<>(list);
this.chunkSize = chunkSize;
}
public static <T> Partition<T> ofSize(List<T> list, int chunkSize) {
return new Partition<>(list, chunkSize);
}
@Override
public List<T> get(int index) {
int start = index * chunkSize;
int end = Math.min(start + chunkSize, list.size());
if (start > end) {
throw new IndexOutOfBoundsException("Index " + index + " is out of the list range <0," + (size() - 1) + ">");
}
return new ArrayList<>(list.subList(start, end));
}
@Override
public int size() {
return (int) Math.ceil((double) list.size() / (double) chunkSize);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment