-3

Can this Java code be re-written by Stream API?

while (true) {
    ...
    if (isTrue()) break;
}

private boolean isTrue() {
    ...
blackeyedcenter
  • 188
  • 1
  • 12
  • 6
    Why do you need to? What's wrong with a loop? Do you actually have a stream of data elements? – M. Prokhorov Oct 16 '19 at 13:12
  • 3
    where does stream come into picture here? – Naman Oct 16 '19 at 13:12
  • I have no need but I want to know whether it can. – blackeyedcenter Oct 16 '19 at 13:17
  • A stream is not infinite. – Joakim Danielson Oct 16 '19 at 13:21
  • @JoakimDanielson are you [sure](https://www.baeldung.com/java-inifinite-streams)? – Kayaman Oct 16 '19 at 13:21
  • I don't think that that's what Streams are for. Think of streams like an assembly line. The assembly line has a beginning (`myList.stream()`) and somewhere it has an end (`collect(Collectors.toList())`). This assembly line starts with empty boxes and at the first station someone puts a smartphone in each box. At the second station someone else checks the boxes if they all have a phone in it and removes the empty boxes (`filter()`) and at another station someone puts earplugs in the box... and so on.. Now your `while` loop does not actually fit in that image if you don't have a stream. – GameDroids Oct 16 '19 at 13:21
  • 1
    You could probably abuse streams to do it, with a suitable `map()` and `anyMatch()/allMatch()`. But why bother writing bad code? – Kayaman Oct 16 '19 at 13:23
  • 1
    @Kayaman Thanks, I hadn't seen that or had the need to reasearch it. Something new learned today :) – Joakim Danielson Oct 16 '19 at 13:24
  • @blackeyedcenter take a look at this post https://stackoverflow.com/questions/20746429/limit-a-stream-by-a-predicate – Villat Oct 16 '19 at 13:27
  • Thank you for your all comments! They are useful for me. – blackeyedcenter Oct 17 '19 at 06:21

2 Answers2

7

This is horrible code, there's no reason ever to use this. Streams are an additional tool to regular loops, they're not a replacement for for and especially while loops.

// If you use this code seriously somewhere, I will find you
IntStream.generate(() -> 0)
    .peek(i -> {
        // Any custom logic
        System.out.println(i);
    })
    .noneMatch(i -> isTrue());

The code generates zeroes infinitely, peeks in the stream to perform custom logic, then stops when noneMatch evaluates to true.

The above is equivalent to the code in the question, which can be written far more succinctly as

do {
    // custom logic
} while(!isTrue());
Kayaman
  • 72,141
  • 5
  • 83
  • 121
0

You cannot replace or rewrite while loop with Stream API. Stream API reads values from Stream. while (true) is not reading data from any stream. It is simply a infinite loop.

Sujay Mohan
  • 933
  • 7
  • 14