[英]Iterate a list in starting at a given index in a circular manner using java 8 IntStream and get the index of first element matching the condition
问题陈述:需要以循环方式迭代的对象列表,从给定的索引开始并迭代,直到我们回到同一个索引。 需要评估一个条件,并且应该返回与该条件匹配的第一个元素的索引。
所以这就像一个满足条件的项目的下一个按钮
班上
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.