What\'s the best way to iterate over a list while processing 2 elements at the same time?
Example:
List strings = Arrays.asList(\"item
List<String> strings = Arrays.asList("item 1", "item 2", "item 3", "item 4");
for(int i = 0; i < strings.size(); i++){
if(i½2 = 0){
String first = strings.get(i);
System.out.print("First [" + first + "] ");
}else{
String second = strings.get(i + 1);
System.out.println("- Second [" + second + "]");
}
}
Just increase i
by 2:
for(int i = 0; i < strings.size(); i += 2) {
For performance, I will recommend you to compute the size of the list only one and not create a new string at each new loop.
List<String> strings = Arrays.asList("item 1", "item 2", "item 3", "item 4");
int length = strings.size();
String first, second = null;
for(int i = 0; i < length; i += 2){
...
}
for(int i = 0; i < strings.size(); i++){
String first = strings.get(i++);
String second = null;
if(strings.size() > i){
second = strings.get(i);
}
System.out.println("First [" + first + "] - Second [" + second + "]");
}
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
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 + "]");
}