Home > other >  How to make findAll stop on first predicate
How to make findAll stop on first predicate

Time:08-09

I've got a question if I'm somehow able to make this code working like this:

If it matches the first predicate: (it.controller == controllerName && it.actions.contains(actionName)), it finds only those, which match this predicate and it doesn't find from those underneath.

If it doesn't find anything from first predicate, then it goes to second one and finds all which match second predicate, but don't match the third one.

 ArrayList rule = rules.findAll {
            (it.controller == controllerName && it.actions.contains(actionName)) 
            ||
            (it.controller == controllerName && it.actions.contains("*")) 
            ||
            (it.controller == "*" && it.actions.contains("*"))
}

CodePudding user response:

I do not know if this is the answer you are expecting but something like this?

rules.stream().filter(it -> it.controller == controllerName && it.actions.contains(actionName))
.filter(it -> it.controller == controllerName && it.actions.contains("*"))
.filter(it -> it.controller == "*" && it.actions.contains("*"))
.collect(Collectors.toList());

CodePudding user response:

If i understood the question correctly, this should work:

def filterFirst(List list, List<Closure> filters) {
        return filters
                .collect { list.findAll(it) }
                .find { it.size() != 0 }
}

Then, just do

filterFirst(rules, [
        { it.controller == controllerName && it.actions.contains(actionName) },
        { it.controller == controllerName && it.actions.contains("*") },
        { it.controller == "*" && it.actions.contains("*") }
])

CodePudding user response:

Use findFirst() instead, here's are some good references: https://www.baeldung.com/java-stream-findfirst-vs-findany and Find first element by predicate

  • Related