Created
August 9, 2020 05:23
-
-
Save AnkitKiet/6c5fd34d390062555c80eb3b0d7a4de6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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