Combining two Immutable lists with inject

爱⌒轻易说出口 提交于 2019-12-11 17:34:37

问题


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.


回答1:


//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}


来源:https://stackoverflow.com/questions/19286182/combining-two-immutable-lists-with-inject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!