Reputation: 941
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?
Upvotes: 1
Views: 978
Reputation: 26076
Not much, that can be done here, streams are great for mapping, filtering, aggregating, collecting... Here you only have side effects for every element. You might wanna use some of functional goodness of streams by applying mapping:
IntStream.range(0, a.length).map(i -> a[i]).forEach(el -> {
if (isOpenToken(el)) {
stack.push(el);
} else {
matches(stack.pop(), el);
}
});
Upvotes: 1