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 = []

namn.each{
mylist << it
}

println mylist

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

namn2.each{
mylist2 << it
}

println mylist2


That will be the output of this:

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

[/Sixten/1.1.0.235/, /Sixten/1.1.0.331/]


I know want to Exchange it to be

[Sixten-1.1.0.235.nupkg, Sixten-1.1.0.331.nupkg]


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

[http://myurl/Sixten-1.1.0.235.nupkg, http://myurl/Sixten-1.1.0.331.nupkg]


HOW?

Answer Source

How about this:

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

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-1.1.0.235.nupkg, http://myurl/Sixten-1.1.0.331.nupkg]

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