将值从字符串排序到映射 groovy

Sort values from sting to map groovy

我有一个简单的任务,但我坚持逻辑。

我有


def setType = "test.1gb, test.2gb, test.4gb, nontest.1gb, nontest.4gb, stage.10gb"
def rep = "1, 2"

我需要排序映射,我用switch casefor。但我不会说我喜欢这个解决方案,因为它不灵活。如果我添加一个新类型,我需要编辑 switch case 构造。

我打算使用 for 循环,但我想念如何正确添加信息以映射,我想我应该使用循环。也许有更好的方法? 我试了,但是有问题

def test = [:]
for(type in setType.split(', ')){       
    for(r in rep.split(', ')){

test += "${type.split('\.')}":[ size: type, rep: r, msg: "hello" ]
  }
}

如何快速构建地图以获取下一个?

def test = [
test: [[size:"test.1gb", rep:1, msg:"something"], [size:"test.1gb", rep:2, msg:"something]],
nontest:[[size:"nontest.1gb",rep:1, msg:"something"], [size:"nontest.1gb",  rep:2, msg:"something]]
]

我不是 100% 是你的意思,而是这样的?

def setType = "test.1gb, test.2gb, test.4gb, nontest.1gb, nontest.4gb, stage.10gb"
def rep = "1, 2"

def result = setType.split(', ')                               // Split the setType string
        .groupBy { it.split('\.').head() }                    // Group by the first part of the word
        .collectEntries { key, values ->                       // Then collect a map
    def elements = [values, rep.split(', ').toList()]
        .combinations()                                        // Get all combinations of the prefixed word and the rep values
        .collect {                                             // Collect them into a list
            [ size: it[0], rep: it[1] as int, msg: 'Hello' ]   // Where each combination makes a map
        }
    [key, elements]                                            // The result map has the first part of the word as the key
}

assert result == [
    test:[
        [size:'test.1gb', rep:1, msg:'Hello'],
        [size:'test.2gb', rep:1, msg:'Hello'],
        [size:'test.4gb', rep:1, msg:'Hello'],
        [size:'test.1gb', rep:2, msg:'Hello'],
        [size:'test.2gb', rep:2, msg:'Hello'],
        [size:'test.4gb', rep:2, msg:'Hello']
    ],
    nontest:[
        [size:'nontest.1gb', rep:1, msg:'Hello'],
        [size:'nontest.4gb', rep:1, msg:'Hello'],
        [size:'nontest.1gb', rep:2, msg:'Hello'],
        [size:'nontest.4gb', rep:2, msg:'Hello']
    ],
    stage:[
        [size:'stage.10gb', rep:1, msg:'Hello'],
        [size:'stage.10gb', rep:2, msg:'Hello']
    ]
]