概述
groovy对列表的操作功能实在是强大,简洁的语法让人欲罢不能,闲话少说
def "过滤列表"() {
def ages = [20, 36, 42, 56]
def midage = 21..50
expect:
ages.grep(midage) == [36, 42]
println ages.grep(midage)
}
def "list of lists,demo flatten"() {
def list = [[1, 2], [3, 4, 5]].flatten()
expect:
list == [1, 2, 3, 4, 5]
println list
}
def "demo list intersect("() {
def list1 = [1, 2, 3]
def list2 = [2, 3, 4]
expect: "求交集"
list1.intersect(list2) == [2, 3]
}
def "demo list disjoint("() {
expect: "不交"
assert [1, 2, 3].disjoint([4, 5, 6])
}
def "demo list pop,like stack("() {
def list = [1, 2, 3]
def popped = list.pop()
expect:
popped == 3
list == [1, 2]
}
def "列表排序和反转"() {
assert [1, 2].reverse() == [2, 1]
assert [3, 1, 2].sort() == [1, 2, 3]
def list = [[1, 0], [0, 1, 2]]
when: "根据第一个元素排序,默认升序 asc"
list = list.sort { a, b -> a[0] <=> b[0] }
then:
list == [[0, 1, 2], [1, 0]]
when: "根据size大小来排序"
list.sort { item -> item.size() }
then:
list == [[1, 0], [0, 1, 2]]
}
def "两种方法,列表元素去重"() {
def x = [1, 1, 1]
expect:
assert [1] == new HashSet(x).toList()
assert [1] == x.unique()
}
def "列表去null"() {
def x = [1, null, 1]
expect:
assert [1, 1] == x.findAll { it != null }
assert [1, 1] == x.grep { it }
}
最后
以上就是个性手套为你收集整理的groovy学习之列表操作--操作列表元素的全部内容,希望文章能够帮你解决groovy学习之列表操作--操作列表元素所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复