Grant Edwards
Grant Edwards

Reputation: 37

How do you merge indexes of two lists in Groovy?

I have two lists that I need to merge into a new list, but the new list needs to contain merged indexes of the original lists. For example:

List1 = [1, 2, 3]
List2 = [a, b, c]

I need the output to be:

finalList = [1a, 2b, 3c]

I need to be able to do this in groovy. I appreciate any help you can provide.

Upvotes: 1

Views: 1137

Answers (2)

Nir Alfasi
Nir Alfasi

Reputation: 53525

The following is very close to doelleri's solution:

In Groovy 2.4+

println ([list1, list2].transpose().collect{it -> it[0] + it[1]})

OUTPUT

[1a, 2b, 3c]

Upvotes: 0

doelleri
doelleri

Reputation: 19682

Assuming both lists are the same size, in Groovy 2.4+,

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

assert ['1a', '2b', '3c'] == list1.withIndex().collect { it, index -> it + list2[index] }

Alternatively and a bit more simply in Groovy 1.5+,

assert ['1a', '2b', '3c'] == [list1, list2].transpose()*.sum()

Upvotes: 2

Related Questions