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