Edición en java construcción corriente perezoso

suraj1291993:

Estaba buscando en este enlace para la construcción corriente perezosa y trató de usarlo para uno de mis casos.

Mi corriente primaria tiene algunas operaciones que se necesitan para hacer el Stream.onClose () .

En mi lógica personalizada, utilizo iterador de Stream.iterator () para el procesamiento de flujos.

Esto funcionaba bien el consumo de la corriente real. Pero, cuando solía Stream.flatMap () para la construcción de una corriente perezosa, onClosela función se llama cuando comienzo iteración, lo que a su vez, crea problemas para mí.

He intentado esto en zulu-opendjk 1.8.0_222 y 13. Estoy frente a esta excepción, tanto en los entornos.

introducir descripción de la imagen aquí

You can reproduce the problem with the below code.

import java.util.*;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class TestStreamIterator
{
    public static void main(String args[])
    {
        Stream<String> stream1 = getStream();
        stream1.iterator().forEachRemaining(System.out::println);

        Stream<String> stream2 = Stream.of(1).flatMap(integer -> getStream());
        stream2.iterator().forEachRemaining(System.out::println);
    }

    private static Stream<String> getStream()
    {
        List<String> values = Arrays.asList("a", "b", "c");

        MyIterator iterator = new MyIterator(values);
        Stream<String> stream = StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.NONNULL | Spliterator.IMMUTABLE), false).onClose(iterator::close);

        return stream;
    }

    private static class MyIterator implements Iterator<String>, AutoCloseable
    {
        private Iterator<String> iterator;

        public MyIterator(List<String> values)
        {
            iterator = values.iterator();
        }

        @Override
        public boolean hasNext()
        {
            return iterator.hasNext();
        }

        @Override
        public String next()
        {
            return iterator.next();
        }

        @Override
        public void close()
        {
            throw new IllegalStateException("Should not come here");
        }
    }
}

My understating is, when using flatMap; close method of Stream.of(1) only should be called. Not of the stream created inside flatMap function.

I was expecting the onClose function to be invoked only when the stream is closed. But, I am not sure where the stream is getting closed.

Any help on solving this case would also be helpful.

xtratic :

When you call flatMap(integer -> getStream()) here:

Stream<String> stream2 = Stream.of(1).flatMap(integer -> getStream());
stream2.iterator().forEachRemaining(System.out::println);

You are calling this method:

Iterator

<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);

Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream. (If a mapped stream is null an empty stream is used, instead.)

So as the documentation says, the mapped stream you pass into this method (from getStream() which is a Stream over a MyIterator) will be closed, which it is, then (as defined in onClose of that Stream) it calls MyIterator.close() which throws the exception.


Addressing your comment since you don't seem to follow:

Stream<String> stream2 = Stream.of(1).flatMap(integer -> getStream());

Crea una corriente que perezosamente se asignarán a los contenidos de una corriente parcial cuando lo lea. Cuando ese sub-corriente se carga en la corriente principal de la sub-corriente será cerrado.

stream2.iterator().forEachRemaining(System.out::println);

Se lee de la corriente principal, que mapea a la sub-secuencia, que lee todos los sub-corriente continuación, cierra la sub-secuencia que entonces las llamadas Stream.onClose()que se pideMyIterator.close()

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=313182&siteId=1
Recomendado
Clasificación