1
\$\begingroup\$

I want to produce a Stream<Pixel> from a Pixel[][]. My code for this is extremely verbose so I suspect I am doing something bad.

Please provide me some advice on how to make my code shorter and cleaner.

private Stream<Pixel> stream() {
    Iterable<Pixel> iterable = new Iterable<Pixel>() {
        @Override
        public Iterator<Pixel> iterator() {
            return new Iterator<Pixel>() {
                private int row = 0;
                private int col = 0;

                @Override
                public boolean hasNext() {
                    return row < height && col < width;
                }

                @Override
                public Pixel next() {
                    Pixel pixel = pixels[row][col];

                    if (col == width - 1) {
                        col = 0;
                        row++;
                    } else {
                        col++;
                    }

                    return pixel;
                }

                @Override
                public void remove() {
                    throw new RuntimeException("nope");
                }
            };
        }
    };

    return StreamSupport.stream(iterable.spliterator(), false);
}

For example, in Python I could do something like:

def stream():
    for row in pixels:
        for pixel in row:
            yield pixel

Which is certainly much more concise and understandable.

\$\endgroup\$
1
1
\$\begingroup\$

You can of course use the Arrays.stream() (twice, because it's a 2D array)

Something along these lines:

private Stream<Pixel> stream() {
  return Arrays.stream(pixels).flatMap(Arrays::stream);
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.