Created
February 29, 2024 18:36
-
-
Save satyajitbaral/0a095fec6e5676602daca49c083b29b4 to your computer and use it in GitHub Desktop.
Partition a list
This file contains hidden or 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
package sj.util; | |
import java.util.AbstractList; | |
import java.util.ArrayList; | |
import java.util.Collection; | |
import java.util.List; | |
import org.springframework.lang.NonNull; | |
/** | |
* The type Partition. | |
* | |
* @param <T> the type parameter | |
*/ | |
public final class Partition<T> extends AbstractList<List<T>> { | |
/** The List. */ | |
private final List<T> list; | |
/** The Chunk size. */ | |
private final int chunkSize; | |
/** | |
* Instantiates a new Partition. | |
* | |
* @param list the list | |
* @param chunkSize the chunk size | |
*/ | |
Partition(@NonNull Collection<T> list, int chunkSize) { | |
this.list = new ArrayList<>(list); | |
this.chunkSize = chunkSize; | |
} | |
/** | |
* Of size partition. | |
* | |
* @param <T> the type parameter | |
* @param list the list | |
* @param chunkSize the chunk size | |
* @return the partition | |
*/ | |
@NonNull | |
public static <T> Partition<T> ofSize(@NonNull Collection<T> list, int chunkSize) { | |
return new Partition<>(list, chunkSize); | |
} | |
/** | |
* Get list. | |
* | |
* @param index the index | |
* @return the list | |
*/ | |
@Override | |
@NonNull | |
public List<T> get(int index) { | |
int start = index * chunkSize; | |
int end = Math.min(start + chunkSize, list.size()); | |
if (start > end) { | |
throw new IndexOutOfBoundsException( | |
String.format("Index %d is out of the list range <0,%d>", index, size() - 1)); | |
} | |
return new ArrayList<>(list.subList(start, end)); | |
} | |
/** | |
* Size int. | |
* | |
* @return the int | |
*/ | |
@Override | |
public int size() { | |
return (int) Math.ceil((double) list.size() / (double) chunkSize); | |
} | |
/** | |
* To string string. | |
* | |
* @return the string | |
*/ | |
@Override | |
public String toString() { | |
return "Partition{" + "list=" + list + ", chunkSize=" + chunkSize + "} " + super.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment