简体   繁体   中英

how to append a list of lists in Groovy

How do I append a list of lists in a purely functional way in groovy? Like if I have a list in variable "a", with a method "b" that returns a list, I can do this:

a.*b
=> [[1, 2], [3, 4, 5], [6]]

but what I really want is:

[1, 2, 3, 4, 5, 6]

This would be easy for example in the Scheme programming language:

(define foo '((1 2) (3 4 5) (6)))
(apply append foo)
=> (1 2 3 4 5 6)

how to do (apply append list-of-lists) in groovy? I know I can do flatten() but that goes arbitrarily deep, and that's not what I want.

Your example code shows the spread-operator. So instead of using that, you can use collectMany .

If you prefer to build the intermediate result and then "apply" one function to merge all lists, you can use sum , which on an array concats all elements.

def a = [[b:[1]],[b:[2,[3]]]]

println(a.collectMany{ it.b })
// → [1, 2, [3]]

println(a*.b.sum())
// → [1, 2, [3]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM