Search code examples
groovy

Groovy, check if all element in array contain substring


I have a list of filepaths, I would like to return true if all elements contain certain substring (tmp/mydir for example), and false if any of them don't

Example:

def is_true = ['tmp/mydir/file1', 'tmp/mydir/file2', 'tmp/mydir/file3']
def is_false =  ['otherdir/file1', 'tmp/file2', 'tmp/file3']

My current solution is to use findAll() and check the result array matches the size of the input.

def lst = ['tmp/mydir/file1', 'tmp/mydir/file2', 'tmp/mydir/file3']
def validated;
        
validated = lst.findAll{element -> element.contains('tmp/mydir')}
def result = validated.size == lst.size

But I wonder whether there is more direct way.? Please advice.


Solution

  • https://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/Iterable.html#every(groovy.lang.Closure)

    def result = lst.every{element -> element.contains('tmp/mydir')}