如何筛选两个列表并创建一个新列表

时间:2016-07-23 11:08:15

标签: list groovy

如果我有两个String列表,如下所示,并希望根据startsWith逻辑创建一个新的String列表,我该怎么办?

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"]

newList是通过查看pathList中每个元素startsWith newList中的每个元素来创建的。

因此,从上面的pathList/etc/fonts/fonts.conf/var/www/foo.bar被删除,因为它们分别与/etc/fonts/var开始。

我想出了下面的内容,但我相信会有一种更加时髦的方式:

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

1 个答案:

答案 0 :(得分: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)
    }
}
相关问题