2

Problem statement : A list of objects which needs to be iterated over in a circular manner starting from a given index and iterating till we reach back to the same index. A condition needs to be evaluated and the index of the first element matching the condition should be returned.

So this behaves like a next button to a item that meets a condition

The 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 + "]";
}

}

There is a list(named list) having objects of class Code and the index from which we need to start(named ind)-this index keeps changing.

This can be implemented using a for loop as below

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;
        }
    }

I wanted to implement the above using Java 8 IntStream. Please let me know how this can be achieved.

shreya
  • 183
  • 1
  • 1
  • 9
  • 1
    Possible duplicate of [Is there a concise way to iterate over a stream with indices in Java 8?](https://stackoverflow.com/questions/18552005/is-there-a-concise-way-to-iterate-over-a-stream-with-indices-in-java-8) – Naman Oct 24 '18 at 14:30

1 Answers1

2

You can create and concat two int streams, one that starts from startIndex and another that end at startIndex.

    int result = IntStream
                 .concat( 
                         IntStream.range( startIndex, list.size() ), 
                         IntStream.range(0, startIndex) )
                 .filter( i -> list.get(i).isOption() )
                 .findFirst()
                 .orElse(-1);
tsolakp
  • 5,858
  • 1
  • 22
  • 28