Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. package utility;
  2.  
  3. import java.util.AbstractList;
  4. import java.util.ArrayList;
  5. import java.util.Arrays;
  6. import java.util.Collection;
  7. import java.util.List;
  8. import java.util.concurrent.atomic.AtomicInteger;
  9. import java.util.stream.Collectors;
  10.  
  11. public final class Partition<T> extends AbstractList<List<T>> {
  12.  
  13. private final List<T> list;
  14. private final int chunkSize;
  15.  
  16. public Partition(List<T> list, int chunkSize) {
  17. this.list = new ArrayList<>(list);
  18. this.chunkSize = chunkSize;
  19. }
  20.  
  21. public static <T> Partition<T> ofSize(List<T> list, int chunkSize) {
  22. return new Partition<>(list, chunkSize);
  23. }
  24.  
  25. @Override
  26. public List<T> get(int index) {
  27. int start = index * chunkSize;
  28. int end = Math.min(start + chunkSize, list.size());
  29.  
  30. if (start > end) {
  31. throw new IndexOutOfBoundsException("Index " + index + " is out of the list range <0," + (size() - 1) + ">");
  32. }
  33.  
  34. return new ArrayList<>(list.subList(start, end));
  35. }
  36.  
  37. @Override
  38. public int size() {
  39. return (int) Math.ceil((double) list.size() / (double) chunkSize);
  40. }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement