Home > Software design >  OneShot Iterable in Java
OneShot Iterable in Java

Time:08-19

What is the name of the interface in Java that allows a single iteration? Iterable allows multiple iterations AFAIK. My use case is below.

private static void iterateOverArray(double[] values) {
    OneShotIterable<Double> valuesIterable = Arrays.stream(values);
    oneShotIterate(valuesIterable);
}

private static void oneShotIterate(OneShotIterable<Double> valuesIterable) {
    for (double value : valuesIterable) {
        // do stuff
    }
}

I know I can iterate over double[] values but I want to accept the most general input I can.

CodePudding user response:

The specific interface you desire, that supports a for loop and does not carry an implication of supporting multiple iterations, does not exist in Java.

Iterator and Stream are each single-use, but you must do some work to get them from an Iterable.

I am sorry if this is not the answer you hoped for, but it's the true answer.

CodePudding user response:

Do you mean something like this - an Iterable with only one item?

Iterable<Thing> iterable = java.util.Collections.singleton( myThing );

If you mean, you want an Iterable to only be iterated once, then what behaviour are you expecting upon a second iteration? An OnlyOnceException to be thrown?

  •  Tags:  
  • java
  • Related