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);