Adding the ".foreach" capability to a custom container class

I wrote my own container class for my game, similar to ArrayList but different in different ways, anyway I want to write a foreach method that will iterate over the backups array.

I know I could just use it Arrays.stream

, but I'm curious what it would look like to write a custom lambda implementation of the #foreach method to iterate over an array.

Who has the key? Thanks to

Example:

class Container<T> {
    T[] array = new T[200]; 
}

      

Now, let's say I would like to do this:

Container<Fish> fishies = new Container();
fishies.forEach(fish->System::out);

      

+3


source to share


2 answers


You need to implement a method forEach

similar to the interface method Stream

in your class Container

:

void forEach(Consumer<? super T> action) 
{
    for (int i = 0; i < array.length; i++)
        action.accept(array[i]);
}

      



This implementation forEach

is sequential, so it is much simpler than an implementation Stream

that can also be parallel.

I ignore the fact that the T[] array = new T[200];

compilation is not committing as that is a different issue.

+3


source


I suggest you create a method that returns a stream:

Stream<T> stream() {
    return Arrays.stream(array);
    // or probably Arrays.stream(array, 0, size); if it used partially
}

      



This way, users will have not only forEach

, but every operation supported by threads.

+2


source







All Articles