Java 8 rewriting a complex for loop using streams

  • A+
Category:Languages

Is it possible to rewrite a complicated for loop like this just using java 8 streams? Anything I come up with seems more bloated, then just leaving the code as is below with a normal for loop.

public static  boolean isBalanced(String text) {     int count = 0;     for(int i = 0; i < text.length(); i++ ) {         if (text.charAt(i) == ')') {             count--;         } else if (text.charAt(i) == '(') {             count++;         }         if (count < 0) {             return false;         }     }     return count == 0; } 

Using Streams

public static boolean isBalanced2(String text) {     AtomicInteger count = new AtomicInteger(0);      text.chars()         .forEachOrdered(x -> {              if (x == ')') {                  count.getAndDecrement();              } else if (x == '(') {                  count.getAndIncrement();              }         });      return count.get() == 0; } 

It works ok but it iterates through the whole string, when sometimes that might be wasted computation for example in the case of the string ")......"

It doesn't seem possible to exit the stream as soon as count is < 0 ? (And I dont want to throw an exception!)

Thanks

 


You should not.

Lambda and Stream are not replacement for all complicated for loop. While you may use a Stream as you've done, this does not means it is better for the eye (what is easier to understand?) and for performance (you surely lost something due to the AtomicInteger vs int based operation but you could probably use a int[] array instead).

  • You can't exit the loop as soon as possible, unless you use exception, but you can narrow your test a little (and you should bench it). You could probably think of using filter after map operation but that won't make it easier to read.
  • You should probably stick to pure function, eg: you should probably not have a side effect (on the AtomicInteger).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: