简体   繁体   中英

Create comma separated string from 2 lists the groovy way

What I have so far is:

def imageColumns = ["products_image", "procuts_subimage1", "products_subimage2", "prodcuts_subimage3", "products_subimage4"]    
def imageValues = ["1.jpg","2.jpg","3.jpg"]
def imageColumnsValues = []

// only care for columns with values
imageValues.eachWithIndex { image,i ->
  imageColumnsValues <<  "${imageColumns[i]} = '${image}'"
}

println  imageColumnValuePair.join(", ") 

It works but I think it could be better. Wish there was a collectWithIndex ... Any suggestions?

There's no collectWithIndex, but you can achieve the same result with a little effort:

def imageColumns = ["products_image", "procuts_subimage1", "products_subimage2", "prodcuts_subimage3", "products_subimage4"]
def imageValues = ["1.jpg","2.jpg","3.jpg"]

def imageColumnsValues = [imageValues, 0..<imageValues.size()].transpose().collect { image, i ->
    "${imageColumns[i]} = '${image}'"
}

println imageColumnsValues.join(", ")

This takes the list of items and a range of numbers from 0 size(list) - 1, and zips them together with transpose . Then you can just collect over that result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM