2016-07-23 176 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 –

相關問題