gpt4 book ai didi

java - 如何获取列表中的连续值对?

转载 作者:行者123 更新时间:2023-12-01 06:42:16 24 4
gpt4 key购买 nike

我想通过循环数组来获取连续值对:

List values = Arrays.asList("A", "B", "C");
ListIterator<String> it = values.listIterator();
while(it.hasNext()) {
String start = it.previous();
String end = it.next();
}

我如何获得:

A, B
B, C

最佳答案

您可以通过经典的for来实现这一点像这样循环:

public static void main(String[] args) {
List<String> values = Arrays.asList("A", "B", "C");
/*
* You obviously want to output 2 values per iteration,
* that means you have to adjust the condition to iterate to the
* second last index (because of accessing i + 1)
*/
for (int i = 0; i < values.size() - 1; i++) {
System.out.println(values.get(i) + ", " + values.get(i + 1));
}
}

不需要迭代器,我强烈建议不要仅使用 List (原始类型)但是List<String> (指定项目类型)。

关于java - 如何获取列表中的连续值对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54149454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com