Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Iterator Loop once, start in middle

I have an Iterator - placed somewhere in the middle of my collection.

I want to loop over the collection from there on, returning a special element if I find it.

If I reach !hasNext() then I want to start at the begining, but I want to stop if I reach the place where I started first.

The best Idea how to solve that seems currently to save the "first" (wherever the iterator pointed when I started) element and then stop if I find that one again.

And that works as long as items can occure only once in my collection (i.e. in a HasSet).

Any better ideas how to do such thing? Iterator doesn't seem to supply a pointer/number back to me that I could compare.

like image 216
Dr. Azrael Tod Avatar asked Mar 18 '26 08:03

Dr. Azrael Tod


1 Answers

With Guava Iterators (Java 7):

Iterator<YourType> iterator = Iterators.concat(yourIteratorPlaceSomewhereInMiddle, Iterators.limit(yourCollection.iterator(), positionOfSomewhereInMiddle));

With Streams (Java 8):

Optional<YourType> theAnswer = IntStream.iterate(positionOfSomewhereInMiddle, pos -> ++pos)
                                        .map(pos -> pos % sizeOfCollection)
                                        .mapToObj(yourCollection::get)
                                        .limit(sizeOfCollection)
                                        .filter(element -> element is 42)
                                        .findFirst();
like image 57
smac89 Avatar answered Mar 20 '26 21:03

smac89



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!