Skip to content
Advertisement

Java – Iterating over every two elements in a list

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]

Advertisement

Answer

Just increase i by 2:

for(int i = 0; i + 1 < strings.size(); i += 2) {
    String first = strings.get(i);
    String second = strings.get(i+1);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement