What's the best way to iterate over a list while processing 2 elements at the same time?
Example:
List<String> strings = Arrays.asList("item 1", "item 2", "item 3", "item 4");
for(int i = 0; i < strings.size(); i++){
    String first = strings.get(i);
    String second = null;
    if(strings.size() > i + 1){
        second = strings.get(i + 1);
    }
    System.out.println("First [" + first + "] - Second [" + second + "]");
}
Results in:
First [item 1] - Second [item 2]
First [item 2] - Second [item 3]
First [item 3] - Second [item 4]
First [item 4] - Second [null]
I would like to achieve:
First [item 1] - Second [item 2]
First [item 3] - Second [item 4]
                I created the following method using a Java8 BiConsumer:
public static <T> void tupleIterator(Iterable<T> iterable, BiConsumer<T, T> consumer) {
    Iterator<T> it = iterable.iterator();
    if(!it.hasNext()) return;
    T first = it.next();
    while(it.hasNext()) {
        T next = it.next();
        consumer.accept(first, next);
        first = next;
    }
}
use it like this:
List<String> myIterable = Arrays.asList("1", "2", "3");
tupleIterator(myIterable, (obj1, obj2) -> {
    System.out.println(obj1 + " " + obj2);
});
This will output:
1 2
2 3
                        Just increase i by 2:
for(int i = 0; i < strings.size() - 2; i += 2) {
    String first = strings.get(i);
    String second = strings.get(i+1);
                        You need to modify and increment i for the second value, modify the statement:
second = strings.get(i + 1);
to
second = strings.get(++i);
This will increment the i as well, since this seems to be the desired behaviour. 
So your code would be:
List<String> strings = Arrays.asList("item 1", "item 2", "item 3", "item 4");
for(int i = 0; i < strings.size(); i++){
    String first = strings.get(i);
    String second = null;
    if(strings.size() > i + 1){
        second = strings.get(++i); //Change here
    }
    System.out.println("First [" + first + "] - Second [" + second + "]");
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With