Iterating through an array 2 items at a time

2019-08-05 05:04发布

问题:

I have a string array that looks something like {"a","b","c","d"}. Each two consecutive items are pairs and I want to iterate through the array and be able to consider the two strings together. Currently I'm thinking of having a loop and a count to work out where I am in the iteration but is there a simpler/better way?

回答1:

for (int i=0 ; i<a.length ; i+=2) {
    String first = a[i];
    String second = a[i+1];
    ...
}

If the array is provided by a caller, then you might want to handle the case where a.length is not even.



回答2:

So I assume you mean a -> b and c -> d. The classic way to deal with this is a loop that increments two at a time:

for(int i = 0; i < myArray.length; i += 2) {
    final String firstVal = myArray[i];
    final String secondVal = myArray[i + 1];
}


回答3:

A few possibilities.

1)

class PairString {
    String a;
    String b;
}
PairString[] stringPairs;

2)

while (i < array.length) {
    String a = array[i];
    String b = array[i + 1];
    i += 2;
}


回答4:

What about using some math?

final String[] words = { "Foo", "Bar", "Baz", "42" };
final int n = words.length / 2;
for (int i = 0; i < n; i++) {
    System.out.println(words[i * 2] + "-" + words[(i * 2) + 1]);
}


回答5:

I like the loop that increments two at a time as well, but just to add something a little different, you could also make use of IntStream:

final String[] words = { "Foo", "Bar", "Baz", "42" };
IntStream.range(1, words.length).forEach(i -> System.out.println(words[i-1] + words[i]));

Outputs:

FooBar
BarBaz
Baz42