在同时处理 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);
这篇关于Java - 遍历列表中的每两个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!