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]
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…