是否可能使用Java 8流重写像这样复杂的for循环?任何我想出来的都似乎更加臃肿,比起下面使用普通for循环留下的代码。
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;
}
使用流
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;
}
它的工作正常,但是它会遍历整个字符串,有时这可能是浪费计算资源的,例如在字符串 ")......" 的情况下。
当计数小于0时似乎无法立即退出流?(我不想抛出异常!)
谢谢
for (char c : test.toCharArray()) {
(或者等价的代码点). - Tom Hawtin - tacklinetext.chars(). forEachOrdered(x -> { if (x == ')') { count.getAndDecrement(); } else if (x == '(') { count.getAndIncrement(); } }); return count.get() == 0; }
它的功能很好,只是它遍历整个字符串,有时候可能会浪费计算资源,例如在字符串“)......”的情况下。 - Patif (count < 0)
和return count == 0;
更好的做法是解释你想要什么。@Pat - Ryuzaki L