Pregunta

I have two lists that consist of strings, both immmutable:

def list1 = [ "A", "B", "C" ]
list2 = ["D", "E", F"]

List 2 is being returned by a custom function I have made. Is there a way to take these two immutable lists and combine both of their elements with inject? I have tried numerous combinations without success. I have googled extensively for this. I cannot change this to a mutable list. I am aware that it would be much easier to simply combine two lists then make them immutable, but alas, this is not what I am aiming for.

Following is the desired output:

[ "A", "B", "C", "D", "E", F"]

The solution here will be used to solve a larger problem. I am merely simplifying this to the base case.

Thank you.

Edit: I have to use the inject method. I am aware that I can simply use + or iterate through each list with a loop to get the desired result. This is strictly limited to using .inject in Groovy.

¿Fue útil?

Solución

//Set as Immutable
def list1 = ["A", "B", "C"].asImmutable() 
def list2 = ["D", "E", "F"].asImmutable() 

//Supports Immutablity
try {list1 << 'Z'} catch(e){assert e instanceof UnsupportedOperationException} 
try {list2 << 'Z'} catch(e){assert e instanceof UnsupportedOperationException}

//Desired result using "inject"
def result = list2.inject(list1){init, val -> [init] << val}.flatten()
assert result == ['A', 'B', 'C', 'D', 'E', 'F'] 

//Immutable Test
assert list1 == ["A", "B", "C"] 
assert list2 == ["D", "E", "F"]

//Supports Immutablity after operation
try {list1 << 'Z'} catch(e){assert e instanceof UnsupportedOperationException}
try {list2 << 'Z'} catch(e){assert e instanceof UnsupportedOperationException}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top