Search code examples
grailsgroovy

converting set to a map groovy


I have my logic in my postprocess to process the values of devices and files as below :(changed this to set from map as it was overriding the values)

def deviceFiles = devices.inject([] as Set) { deviceFiles, device ->
            def v = device.key.split( /\./ )[0]
            deviceFiles << [ (device.value), files[ v ] ]
        }

output : deviceFiles :[[Acer C6, Tetris.apk], [Motorola Droid Milestone, Tetris.apk], [Acer C6, TheSims3.apk], [HTC Desire, TheSims3.apk]] --- looks good to be displayed

These values are to be passed as a map/properties so that the data would be displayed properly without any cast exceptions, which I am finding tough..

when it is looped through the set

deviceFiles.each { device  ->
            mapping.put("${device}", "${file}")
        }

output : mapping :[HTC Desire:TheSims3.apk, Motorola Droid Milestone:Tetris.apk, Acer C6:Tetris.apk] -- which is not correct (Acer C6:TheSims3.apk has been overriden)

Am I missing something here in sending the expected values into map? or it is not possible to send the values of set through map(as map always eliminates the duplicates when i am iterating through devices) ???


Solution

  • You could use collectEntries:

    def deviceFiles = devices.collectEntries {
        device -> [device.value, device.key.split(/\./)[0]]
    }