0

Possible Duplicate:
Grabbing a segment of an array in Java

I have a String[] which might contain 3, 6, 14 or 20 elements. I want to process 10 elements from the String[] array each time.

(e.g. for 3 or 6 it will loop once and twice for 14 or 20)

Community
  • 1
  • 1
user339108
  • 12,613
  • 33
  • 81
  • 112

5 Answers5

2

You can use Arrays.copyOfRange to obtain subranges of your array.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
0

Are you looking for something like this, assuming a String[] array:

int pos = 0;
while (pos + 10 < array.length) {
    // process array[pos] to array[pos + 9] here
    pos += 10;
}
// process array[pos] to array[array.length - 1] here
WhiteFang34
  • 70,765
  • 18
  • 106
  • 111
0

Use thsi to loop one for each 10 Elements:

int index = 0;
while (index < array.length) do
{
  // process
  index = index + 10;
}
CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
0
String[] arr={"h","e","l","l","o"};
List<String> li = Arrays.asList(arr);
final int divideBy=2;
for(int i=0;i<arr.length;i+=divideBy){
    int endIndex=Math.min(i+divideBy,arr.length);
    System.out.println(li.subList(i,endIndex)); 
}
Emil
  • 13,577
  • 18
  • 69
  • 108
0

Two nested loops:

    int[] nums = new int[14];
    // some initialization
    for (int i = 0; i < nums.length; i++) {
        nums[i] = i;
    }
    // processing your array in chunks of ten elements
    for (int i = 0; i < nums.length; i += 10) {
        System.out.println("processing chunk number " + 
                (i / 10 + 1) + " of at most 10 nums");
        for (int j = i ; j < 10 * (i + 1) && j < nums.length; j++) {
            System.out.println(nums[j]);
        }
    }

Output is

processing chunk number 1 of at most 10 nums
0
1
2
3
4
5
6
7
8
9
processing chunk number 2 of at most 10 nums
10
11
12
13

I've used an int[] and not a String[], but it's the same.

MarcoS
  • 13,386
  • 7
  • 42
  • 63