Mikael Floberg Mikael Floberg -4 years ago 96
Groovy Question

Two lists - Append and exchange

I have this

def url = "http://myurl/".toURL().text
def root = new XmlSlurper().parseText(url)

def namn = root.data.'content-item'.'**'.findAll{ node-> node.name() == 'resourceURI' }*.text()
def mylist = []

mylist << it

println mylist

def namn2 = root.data.'content-item'.'**'.findAll{ node-> node.name() == 'relativePath' }*.text()
def mylist2 = []

mylist2 << it

println mylist2

That will be the output of this:

[http://myurl/, http://myurl/]

[/Sixten/, /Sixten/]

I know want to Exchange it to be

[Sixten-, Sixten-]

and then appended to the first list so it would result like this

[http://myurl/Sixten-, http://myurl/Sixten-]


Answer Source

How about this:

def myList = ['http://myurl/', 'http://myurl/']
def myList2 = ['/Sixten/', '/Sixten/']

myList2 = myList2.collect { list2Entry ->
    list2Entry[1..-2].replaceAll('/', '-') + '.nupkg'

def lst = []
myList.eachWithIndex{ txt, idx ->
    lst << txt + myList2[idx]

println lst

prints: [http://myurl/Sixten-, http://myurl/Sixten-]

First, inside the collect the leading and trailing slashes are removed by removing the first and last char of the strings with [1..-2]. Then the slashes in the middle of the strings are replaced by minus with replaceAll and .nupkg is added with string concatenation.

Inside the eachWithIndex every string from myList is concatenated with the string inside myList2 at the same position and the resulting string is added to the newly created list lst.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download