I have read this post How to use if-else logic in Java 8 stream forEach
The whole point of Java 8 is to write more elegant, readable and concise code. I rewrote this execute method utilizing Java 8 Streams and Lambda but what i end up with doesn't look any different from the Java 7 version.
private static boolean execute(String expression) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : expression.toCharArray()) {
if (isOpenToken(c)) {
stack.push(c);
} else if (stack.isEmpty() || !matches(stack.pop(), c)) {
return false;
}
}
return stack.isEmpty();
}
This is what the method looks like now in Java 8
private static boolean execute(String expression) {
char[] a = expression.toCharArray();
Deque<Character> stack = new ArrayDeque<>();
IntStream.range(0, a.length).forEach(i -> {
if (isOpenToken(a[i])) {
stack.push(a[i]);
} else {
matches(stack.pop(), a[i]);
}
});
return stack.isEmpty();
}
Is there a more elegant way of doing this in Java 8?