2016-07-23 154 views
0

如果我有两个如下所示的字符串列表,并且想根据startsWith逻辑创建一个新的字符串列表,我该怎么做?如何筛选两个列表并创建一个新列表

pathList = ["/etc/passwd/something.txt", 
      "/etc/fonts/fonts.conf" 
      "/var/www/foo.bar", 
      "/some/foo/path/one.txt"] 
notAllowedPathList = ["/etc/fonts", 
         "/var", 
         "/path"] 

newList = ["/etc/passwd/something.txt", "/some/foo/path/one.txt"] 

newListnewList看到是否每个元素在pathListstartsWith每个元素创建。

所以,从上述pathList/etc/fonts/fonts.conf/var/www/foo.bar被除去,因为它们分别startWith /etc/fonts/var

我想出了下面,但我相信会有这样做的更加常规的方式:

def newList = [] 
    pathList.each {String fileName -> 
     notAllowedPathList.find { String notAllowed -> 
      if (fileName.startsWith(notAllowed)) { 
       return true 
      } 
      else { 
       newList << fileName 
      } 
     } 
    } 

回答

0
def pathList = [ 
    "/etc/passwd/something.txt", 
    "/etc/fonts/fonts.conf", 
    "/var/www/foo.bar", 
    "/some/foo/path/one.txt" 
] 

def notAllowedPathList = ["/etc/fonts", "/var", "/path"] 

def newList = pathList.findAll { String fileName -> 
    !notAllowedPathList.any { 
     fileName.startsWith(it) 
    } 
} 
+0

哇,我不知道''可以附加在'any'。你能解释一下它的功能吗? – Anthony

+0

如果被调用的集合中的任何元素在传递给闭包参数时返回真值,那么'any'返回true –

相关问题