在Groovy中,空项通常指的是null
值或空字符串""
。Groovy提供了多种简洁的方式来处理列表中的空项。
def list = [1, null, "hello", "", 2, null, "world"]
def cleanedList = list.findAll { it != null && it != "" }
println cleanedList // 输出: [1, hello, 2, world]
def list = [1, null, "hello", "", 2, null, "world"]
def cleanedList = list.grep { it }
println cleanedList // 输出: [1, hello, 2, world]
def list = [1, null, "hello", "", 2, null, "world"]
def cleanedList = list - [null, ""]
println cleanedList // 输出: [1, hello, 2, world]
def list = [1, null, "hello", "", 2, null, "world"]
list.removeAll([null, ""])
println list // 输出: [1, hello, 2, world]
问题:为什么grep { it }能过滤空项?
原因:Groovy中null
、空字符串""
、空集合等在布尔上下文中会被视为false
,而其他非空值被视为true
。grep
方法会保留使闭包返回true
的元素。
问题:如何自定义空项的定义?
def list = [1, null, "hello", " ", 2, null, "world"]
// 自定义空项包括null、空字符串和仅包含空格的字符串
def cleanedList = list.findAll {
it != null && it.toString().trim() != ""
}
println cleanedList // 输出: [1, hello, 2, world]
以上方法可以根据实际需求选择最适合的方式来清理Groovy列表中的空项。
没有搜到相关的文章