Groovy build a list from two lists

Viewed 38

I have two array list in that form:

def AllowedExtensions = [ '.mxf', '.mov', '.mp4']
def myPaths = [C:\Temp\Media\Media.c2v, C:\Temp\Media\Media.V2C, C:\Temp\Media\toto\test\巨塔の終わり.mp4, C:\Temp\Media\toto\toto.mxf]

I'm trying to build a new list mySelectedPath from myPaths only if it matches one of the extensions from AllowedExtensions I'm looking for the groovy way to do it but can't get it working correctly.

AllowedExtensions.each { mySelectedPath =  myPaths.findAll { it }}

Here is my expected result:

[C:\Temp\MediaNavigator\toto\toto.mxf, C:\Temp\MediaNavigator\toto\test\巨塔の終わり.mp4]

Thank you for any input !

3 Answers

Another solution is to use findResults

allowedExtensions.findResults { ext -> myPaths.find { it.endsWith ext } }

If you want multiple results per extension, try:

allowedExtensions.findResults { ext -> myPaths.findAll { it.endsWith ext } }.flatten()
def AllowedExtensions = [ '.mxf', '.mov', '.mp4']
def myPaths = [
    'C:\\Temp\\Media\\Media.c2v', 
    'C:\\Temp\\Media\\Media.V2C', 
    'C:\\Temp\\Media\\toto\\test\\巨塔の終わり.mp4', 
    'C:\\Temp\\Media\\toto\\toto.mxf'
]

println myPaths.findAll { it.toLowerCase()[it.lastIndexOf('.')..-1] in AllowedExtensions }

Or regex-based:

def AllowedExtensions = [ '.mxf', '.mov', '.mp4']
def myPaths = ['C:\\Temp\\Media\\Media.c2v', 'C:\\Temp\\Media\\Media.V2C', 'C:\\Temp\\Media\\toto\\test\\巨塔の終わり.mp4', 'C:\\Temp\\Media\\toto\\toto.mxf']

def regex = /^.*\.(${AllowedExtensions.join( '|' ).replace( '.', '' )})$/

def res = myPaths.grep{ it ==~ regex }

assert res.toString() == '[C:\\Temp\\Media\\toto\\test\\巨塔の終わり.mp4, C:\\Temp\\Media\\toto\\toto.mxf]'
Related