问题陈述:需要以循环方式迭代的对象列表,从给定索引开始迭代,直到回到同一索引。需要评估一个条件,并返回第一个匹配条件的元素的索引。
因此,这就像满足条件的项目的下一个按钮
类(class)
public class Code {
private String type;
private String description;
private boolean option;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isOption() {
return option;
}
public void setOption(boolean option) {
this.option = option;
}
@Override
public String toString() {
return "Code [type=" + type + ", description=" + description + ", option=" + option + "]";
}
}
有一个列表(名为列表),其中包含类 Code 的对象和我们需要启动的索引(名为 ind) - 该索引不断变化。
这可以使用如下的 for 循环来实现
for(int i=((ind+1)%list.size());i!=ind;i=((i+1)%list.size())) {
Code code = (Code)list.get(i);
if(!code.isOption())
{
System.out.println("Index of the record matched" + i);
break;
}
}
我想使用 Java 8 IntStream 来实现上述内容。请告诉我如何实现这一目标。
最佳答案
您可以创建并连接两个 int 流,一个从 startIndex 开始,另一个从 startIndex 结束。
int result = IntStream
.concat(
IntStream.range( startIndex, list.size() ),
IntStream.range(0, startIndex) )
.filter( i -> list.get(i).isOption() )
.findFirst()
.orElse(-1);
关于java - 使用 java 8 IntStream 以循环方式从给定索引开始迭代列表,并获取与条件匹配的第一个元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52971177/