Sunday, 27 January 2019

Groovy: Duplicate elements of a list


Groovy provides below ways to duplicate the elements of a list.
a.   Using * operator
b.   Using multiply method
c.    Using Collections.nCopies method

HelloWorld.groovy

numbers = [1, 2, 3]
duplicateNumbers1 = numbers * 3
duplicateNumbers2 = numbers.multiply(3)
duplicateNumbers3 = Collections.nCopies(3, numbers)

println "numbers: $numbers"
println "duplicateNumbers1: $duplicateNumbers1"
println "duplicateNumbers2: $duplicateNumbers2"
println "duplicateNumbers3: $duplicateNumbers3"

Output
numbers: [1, 2, 3]
duplicateNumbers1: [1, 2, 3, 1, 2, 3, 1, 2, 3]
duplicateNumbers2: [1, 2, 3, 1, 2, 3, 1, 2, 3]
duplicateNumbers3: [[1, 2, 3], [1, 2, 3], [1, 2, 3]]


Previous                                                 Next                                                 Home

No comments:

Post a Comment