Groovy listings or flattening by level

I am trying to pin two lists. I found a solution using transpose(at this link: Is there any analogue for the Scala 'zip' function in Groovy? ), But the result is not what I expected. I want the lists to be archived! I really mean hush.

Given:

a = [ [1,2,3] , [4,5,6], [7,8,9] ]
b = [ ['a','b','c'] , ['d','e','f'], ['g','h','j']]

Expected Result:

zipped = [ [1,2,3], 
           ['a','b','c'], 
           [4,5,6], 
           ['d','e','f'], (...) ]

But transposing gives me:

[a,b].transpose() = [ [[1,2,3],['a','b','c']]
                      [[4,5,6],['d','e','f']]
                      [[7,8,9],['g','h','j']] ]

I tried to smooth the last list somehow, but there is no leveling. Each individual list is flattened, where I just want to exit the lists of "strings",

+4
source share
3 answers
[a, b].transpose().collectMany { it }
+3
source

flatten() , . inject:

def zip(a,b) {
    [a,b].transpose().inject([]) { result, list -> result + list }
}

def a = [ [1,2,3] , [4,5,6], [7,8,9] ]
def b = [ ['a','b','c'] , ['d','e','f'], ['g','h','j']]

assert zip(a,b) == [
    [1, 2, 3], 
    ['a', 'b', 'c'], 
    [4, 5, 6], 
    ['d', 'e', 'f'], 
    [7, 8, 9], 
    ['g', 'h', 'j']
]
+1

Two ideas entered my head:

def a = [ [1,2,3] , [4,5,6], [7,8,9] ]
def b = [ ['a','b','c'] , ['d','e','f'], ['g','h','j']]

def l = []
[a,b].transpose().collect { it.collect { l << it} }
assert l ==  [[1, 2, 3], ['a', 'b', 'c'], [4, 5, 6], ['d', 'e', 'f'], [7, 8, 9], ['g', 'h', 'j']]


def k = [a,b].transpose().inject([]) {acc, val -> 
    val.collect {acc << it }
    acc
}
assert k ==  [[1, 2, 3], ['a', 'b', 'c'], [4, 5, 6], ['d', 'e', 'f'], [7, 8, 9], ['g', 'h', 'j']]
0
source

Source: https://habr.com/ru/post/1548035/


All Articles