Skip to content
Advertisement

Create a stream that is based on a custom generator/iterator method

How can I create a Stream that creates a number of items based on a custom generate() method?

The question is different from the one referred to. The final result is a Stream, so I could (simplistically) use a “.forach( System.out::println)”.

An example would be: Stream.generate( myGenerateMethod).forEach( System.out::println);

Or a simplistic example would be:

Stream<String> overallStream = Stream.generate( () -> {
    if( generateCounter++ < 5) {
        return "String-" + generateCounter;
    }
    // close the stream
    return null; 
});
overallStream.forEach( System.out::println) ;

UPDATE and SOLUTION: referred to answers often don’t give a Stream. So reopening was better.

maxGenerateCounter = 6;
StreamSupport.stream(Spliterators.spliteratorUnknownSize(new Iterator<String>() {
    int counter = 0;

    @Override
    public boolean hasNext() {
        return counter < maxGenerateCounter;
    }

    @Override
    public String next() {
        // do something
        // check if the 'end' of the Stream is reached
        counter++; // simplistically
        if( counter > maxGenerateCounter) {
            return null; // Not important answer
        }
        return "String-" + counter;
    }
}, Spliterator.IMMUTABLE), false).forEach( System.out::println);

Advertisement

Answer

Thank you, developers!! You inspired me in finding the solution. Many thanks!

My problem was a bit complex, and simplifying let to a over simplified question.

As we can read the many solutions, it looks like Java and Streams is fun to solve!

Experimenting with many answers, this one works. It gives a fairly easy approach of getting a STREAM that easily can be controlled. No double checking of the criteria. I liked those anyXxx( ) answers giving insight!

maxGenerateCounter = 6;
System.out.println( "Using Splitter: ");
StreamSupport.stream(Spliterators.spliteratorUnknownSize(new Iterator<String>() {
    int counter = 0;
    @Override
    public boolean hasNext() {
        // simplistic solution, see below for explanation
        return counter < maxGenerateCounter;
    }
    @Override
    public String next() {
        // executing stuff
        // providing info for 'stopping' the stream
        counter++; // for simplicity
        if( counter > maxGenerateCounter) {
           return null; // this could be any answer. It will be filtered out. 
        }
        return "String-" + counter;
    }
}, Spliterator.IMMUTABLE), false).forEach( System.out::println);

Thank you, contributors, again!

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement