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

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

例:

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]

回答:

只需增加i2:

for(int i = 0; i < strings.size(); i += 2) {

以上是 Java-遍历列表中的每两个元素 的全部内容, 来源链接: utcz.com/qa/414959.html

回到顶部