Java List: 获取相邻元素并循环输出
使用 for 循环遍历列表,判断当前元素与下一个元素是否相邻,如果是,则返回这两个元素。示例代码如下:
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
for (int i = 0; i < list.size() - 1; i++) {
int cur = list.get(i);
int next = list.get(i + 1);
if (next - cur == 1) {
System.out.println(cur + ', ' + next);
}
}
输出结果为:
1, 2
2, 3
3, 4
4, 5
注意,这种方法只能返回相邻的两个元素,如果要返回多个相邻元素,需要进行更复杂的判断。
原文地址: https://www.cveoy.top/t/topic/ohGW 著作权归作者所有。请勿转载和采集!