Best way to split an array in java into smaller arrays?
What's the best way to split an array in a java method into smaller arrays? I want that in any array of sizetakeReceipts(String[])
//Can handle any size array
public void takeReceipts(String[] receipts){
//split array into smaller arrays, and then call handleReceipts(String[]) for every smaller array
}
//This method can only handle arrays with the size of 5 or less
private void handleReceipts(String[] receipts){
myNetworkRequest(receipts);
}
EDIT:
So it looks like copying an array to another array is inefficient. Will something like this work?
public void takeReceipts(String[] receipts){
int limit = 5;
int numOfSmallerArrays = (receipts.length/limit)+(receipts.length%limit);
int from = 0;
int to = 4;
for (int i = 0; i < numOfSmallerArrays; i++){
List<String> subList = Arrays.asList(receipts).subList(from, to);
from =+ limit;
to =+ limit;
}
}
source to share
You can use Arrays.copyOfRange()
:
int from = 0;
int to = 4;
String[] subArray = Arrays.copyOfRange(receipts, from, to)
source to share
If you use List<String>
instead of String[]
arrays, you can do the partitioning very economically:
List<String> subList = Arrays.asList(receipts).subList(from, to);
This approach does not make a copy of your array, providing a read-only view of the original receipt array.
static final int LIMIT = 10;
public static void process(List<String> small) {
if (small.size() > LIMIT) {
System.out.print("Array is too big: "+small.size());
return;
}
for (String s : small) {
System.out.print(s+" ");
}
System.out.println();
}
public static void processBig(String[] receipts) {
int numChunks = ((receipts.length+LIMIT-1)/LIMIT);
int from = 0;
int to = LIMIT;
List<String> bigList = Arrays.asList(receipts);
for (int i = 0 ; i != numChunks ; i++) {
List<String> subList = bigList.subList(from, to);
process(subList);
from += LIMIT;
to += LIMIT;
if (to >= receipts.length) {
to = receipts.length;
}
}
}
The implications of this approach are that changes made to the original elements of the array become "visible" through the view and that you cannot change the resulting array in any way subList
.
source to share
public void takeReceipts(String[] receipts){
for (int i=0; i< receipts.length; i+=5)
handleReceipts(Arrays.copyOfRange(receipts, i, Math.min(i+4, receipts.length-1)));
}
private void handleReceipts(String[] receipts){
}
OR
public void takeReceipts(String[] receipts){
for (int i=0; i< receipts.length; i+=5)
handleReceipts(Arrays.asList(receipts).subList(i, Math.min(i+4, receipts.length-1)));
}
private void handleReceipts(List<String> receipts){
}
source to share