英文:
Return lazy evaluation of list of boolean statements , with any of it true
问题
有一系列布尔决策,每个决策都有不同的条件需要评估。如果其中任何一个评估为true,就应该返回。问题是,我不希望它们被急切地评估。我这里有两种实现,第一种可以工作,但是我有10个这样的决策要做,所以我希望将它们全部作为列表获取,但是一旦我把它们放入列表/流中,它就会评估所有的决策,从而失去了目的。我想要的是,如果任何一个条件评估为true,它应该立即停止并返回,其余条件不应该被执行。
```java
BooleanSupplier a = () -> compute("bb");
BooleanSupplier b = () -> computeSecond("aa");
// 这个可以工作
System.out.println("Lazy匹配 => " + lazyMatch(a, b));
// 这个不可以
System.out.println("Lazy匹配列表 => " + lazyMatchList(Stream.of(a, b)));
static boolean lazyMatch(BooleanSupplier a, BooleanSupplier b) {
return a.getAsBoolean() || b.getAsBoolean();
}
static boolean lazyMatchList(Stream<BooleanSupplier> lazyBooleanList) {
return lazyBooleanList.anyMatch(BooleanSupplier::getAsBoolean);
}
static boolean compute(String str) {
System.out.println("执行中...");
return str.contains("ac");
}
// computeSecond类似于compute
英文:
I have a series of boolean decision, each having a different condition to evaluate. If any of it evaluates to true it should return. Problem is, I do not want them to be eagerly evaluated. I have two implementations here, the first one works, but i have 10 such decisions to make so i want to get them all as a list, as soon as I put them into list/stream it evaluates all the decisions and fails the purpose. What I want is, if any of the condition evaluates to true it should stop right there and return, rest of the conditions should not get executed.
BooleanSupplier a = () -> compute("bb");
BooleanSupplier b = () -> computeSecond("aa");
// this works
System.out.println("Lazy match => " + lazyMatch(a, b));
// this doesn't
System.out.println("Lazy match list => " + lazyMatchList(Stream.of(a,b)));
static boolean lazyMatch(BooleanSupplier a, BooleanSupplier b) {
return a.getAsBoolean() || b.getAsBoolean();
}
static boolean lazyMatchList(Stream<BooleanSupplier> lazyBooleanList) {
return lazyBooleanList.anyMatch(BooleanSupplier::getAsBoolean);
}
static boolean compute(String str) {
System.out.println("executing...");
return str.contains("ac");
}
// compute2 is something similar to compute
答案1
得分: 1
尝试这个:
List<Predicate<String>> predicates = Arrays.asList(this::compute1, this::compute2, ...);
boolean anyTrue(String str) {
return predicates.stream()
.anyMatch(p -> p.test(str));
}
这会在第一个谓词返回 true 时返回 true
。
将这个方法用作过滤谓词:
someStringStream.filter(this::anyTrue)...
英文:
Try this:
List<Predicate<String>> predicates = Arrays.asList(this::compute1, this::compute2, ...);
boolean anyTrue(String str) {
return predicates.stream()
.anyMatch(p -> p.test(str));
}
This returns true
when the first predicate returns true.
Use the method as a filter predicate:
someStringStream.filter(this::anyTrue)...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论