Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Iterating over every two elements in a list

Tags:

java

iterator

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]
like image 613
stikkos Avatar asked Apr 16 '13 09:04

stikkos


3 Answers

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
like image 126
Benjamin M Avatar answered Oct 18 '22 04:10

Benjamin M


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);
like image 45
hyde Avatar answered Oct 18 '22 05:10

hyde


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 + "]");
}
like image 7
Habib Avatar answered Oct 18 '22 05:10

Habib