Search code examples
javaiteratorinfinite

How can I make an iterator that never ends?


I was just wondering what the easiest way to iterate over a set indefinitely, i.e. when it reaches the end it next(); calls the first object. I'm assuming that this is not an already predefined function in Java, so just looking for the easiest way to implement this in Java.


Solution

  • There's a method in the excellent Google Collections library which does this:

    Set<String> names = ...;
    Iterable<String> infinite = Iterables.cycle(names);
    

    (I can't recommend the Google Collections library strongly enough. It rocks very hard. I'm biased as I work for Google, but I think pretty much every Googler writing Java would tell you how useful the collections are.)