groovy学习之列表操作--操作列表元素
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 }
}
阅读更多
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇:没有了
- 下一篇:没有了