在同时处理 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模板网!
Java从数组中删除重复项?Java Remove Duplicates from an Array?(Java从数组中删除重复项?)
Eclipse 的 egit 插件egit plugin for Eclipse(Eclipse 的 egit 插件)
Gitlab 无法打开 git-upload-pack 错误Gitlab cannot open git-upload-pack error(Gitlab 无法打开 git-upload-pack 错误)
如何修复调用失败来自服务器的意外响应:在 AnHow to fix Invocation failed Unexpected Response from Server: Unauthorized in Android studio(如何修复调用失败来自服务器的意外响应:在
如何在 Eclipse 中添加 GitLab 存储库?How to add GitLab repository in Eclipse?(如何在 Eclipse 中添加 GitLab 存储库?)
AES 加密,解密文件中有多余的垃圾字符AES encryption, got extra trash characters in decrypted file(AES 加密,解密文件中有多余的垃圾字符)