There are multiple ways to create a list from another
list.
a.
Using Spread operator
b.
Calling the constructors of ArrayList,
LinkedList
c.
Adding all the elements of this list
explicitly
Using Spread operator
HelloWorld.groovy
evenNumbers = [0, 2, 4, 6] oddNumbers = [1, 3, 5, 7] primeNumbers = [2, 3, 5, 7, 11] allNumbers = [*evenNumbers, *oddNumbers, *primeNumbers] println allNumbers
Output
[0, 2, 4, 6, 1, 3, 5, 7, 2, 3, 5, 7, 11]
Calling constructors
of ArrayList and LinkedList
HelloWorld.groovy
evenNumbers = [0, 2, 4, 6] list1 = new ArrayList(evenNumbers) list2 = new LinkedList(evenNumbers) println "evenNumbers : ${evenNumbers}" println "list1 : ${list1}" println "list2 : ${list2}"
Output
evenNumbers : [0, 2, 4, 6]
list1 : [0, 2, 4, 6]
list2 : [0, 2, 4, 6]
Adding all the elements
of this list explicitly
HelloWorld.groovy
evenNumbers = [0, 2, 4, 6] list1 = new ArrayList() list1.addAll(evenNumbers) println evenNumbers println list1
Output
[0, 2, 4, 6]
[0, 2, 4, 6]
No comments:
Post a Comment