All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.wizarius.orm.utils.WizariusArrayPartition Maven / Gradle / Ivy

There is a newer version: 0.0.27.3
Show newest version
package com.wizarius.orm.utils;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Vladyslav Shyshkin
 * Date: 25.09.2019
 * Time: 15:32
 * 

* final List numbers = Arrays.asList(1,2,3,4,5,6,7); *

* System.out.println(Partition.ofSize(numbers, 3)); * System.out.println(Partition.ofSize(numbers, 2)); *

* [[1, 2, 3], [4, 5, 6], [7]] * [[1, 2], [3, 4], [5, 6], [7]] *

* https://e.printstacktrace.blog/divide-a-list-to-lists-of-n-size-in-Java-8/ */ public class WizariusArrayPartition extends AbstractList> { private final List list; private final int chunkSize; public WizariusArrayPartition(List list, int chunkSize) { this.list = new ArrayList<>(list); this.chunkSize = chunkSize; } /** * Split array to partition of size * * @param list source list * @param chunkSize max count elements in partition array * @param list * @return partitions */ public static WizariusArrayPartition ofSize(List list, int chunkSize) { return new WizariusArrayPartition<>(list, chunkSize); } /** * Get partition by index * * @param index index of partition * @return partition list */ @Override public List 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)); } /** * Size of partition * * @return partition size */ @Override public int size() { return (int) Math.ceil((double) list.size() / (double) chunkSize); } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy