Java - 遍历列表中的每两个元素

2022-01-10 00:00:00 iterator java

在同时处理 2 个元素的同时迭代列表的最佳方法是什么?

What's the best way to iterate over a list while processing 2 elements at the same time?

例子:

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 + "]");
}

结果:

First [item 1] - Second [item 2]
First [item 2] - Second [item 3]
First [item 3] - Second [item 4]
First [item 4] - Second [null]

我想实现:

First [item 1] - Second [item 2]
First [item 3] - Second [item 4]

推荐答案

只需将i加2即可:

for(int i = 0; i < strings.size() - 2; i += 2) {
    String first = strings.get(i);
    String second = strings.get(i+1);

相关文章