Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Guava Iterables.cycle as a circular list impl

I have a List<Widget> and am looking for the most efficient/elegant solution to loop over it, again and again (kind of like a round robin algorithm):

// Returns a list of 20 widgets, with an id of 1 - 20 respectively.
List<Widget> widgets = getWidgets();
Widget widget = pickWidget(); // Returns the 1st widget with id = 1.
widget = pickWidget(); // Returns the 2nd widget with id = 2.
widget = pickWidget(); // Return the 3rd widget with id = 3.
// ..etc.
widget = pickWidget(); // Returns the 19th widget with id = 19.
widget = pickWidget(); // Returns the 20th widget with id = 20.
widget = pickWidget(); // Returns the 1st widget with id = 1 (it cycle back).

That's the usage, for the implementation the best I've been able to find is Guava's Iterables.cycle(...):

Widget pickWidget() {
    for(Widget w : Iterables.cycle(widgets)) {
        return w;
    }
}

The problem is that cycle doesn't leave a marker inside widgets so that it can "remember" where it let off the last time pickWidget() was called.

Any ideas here? Apache's CircularFifoQueue seems close but no cigar, as I don't want anything popped off the queue, I just want it to cycle over the same list time and time again as it is called.

like image 604
smeeb Avatar asked Oct 17 '25 08:10

smeeb


1 Answers

It doesn't need to leave any marker. The Iterator of the Iterable returned by cycle() keeps that mark internally. All you need is to keep a reference to this iterator:

private Iterator<Widget> cyclingIterator = Iterables.cycle(widgets).iterator();

public Widget pick() {
    return cyclingIterator.next();
}

Or simply, since you don't actually need the Iterable, but only the iterator:

private Iterator<Widget> cyclingIterator = Iterators.cycle(widgets);

public Widget pick() {
    return cyclingIterator.next();
}
like image 168
JB Nizet Avatar answered Oct 19 '25 22:10

JB Nizet



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!