使用" flattening"将集合添加到其他集合在Groovy中

时间:2016-02-04 11:35:09

标签: groovy

这里是Groovy 2.4.x.我有一个Set<String>,并且需要编写一些方法来动态地将其他字符串添加到该集合中,具体取决于它的内容:

Set<String> resolveAllColors(Set<String> colors) {
    if(colors.contains('Rainbow')) {
        colors << getAllRainbowColors()
    } else if(colors.contains('Red')) {
        colors << getAllRedishColors()
    }
}

Set<String> getAllRainbowColors() {
    [
        getAllRedishColors(),
        'Orange',
        'Yellow',
        'Green',
        'Blue',
        'Indigo',
        'Violet'
    ]
}

Set<String> getAllRedishColors() {
    [
        'Rose',
        'Maroon'
    ]
}

正如您所看到的,如果我的初始Set<String>包含"Red",那么我想再添加一些&#34; redish&#34;颜色到那一组。但如果它包含"Rainbow",那么我想添加所有&#34; redish&#34;颜色以及该组的其他几个字符串。

当我使用以下驱动程序运行此代码时:

class Driver {
    static void main(String[] args) {
        new Driver().run()
    }

    void run() {
        Set<String> colors = [ 'White', 'Red' ]
        println resolveAllColors(colors)
    }

    // All the methods mentioned above
}

...然后我得到以下输出:

[ White, [ Rose, Maroon ] ]

我想要:

[ White, Rose, Maroon ]

当我将colors设置为Set<String> colors = [ 'White', 'Rainbow' ]时,我得到了:

[ White, [ [ Rose, Maroon ], Orange, Yellow, Green, Blue, Indigo, Violet ] ]

而不是:

[ White, Rose, Maroon, Orange, Yellow, Green, Blue, Indigo, Violet ]

为什么我会获得所有这些嵌套集,以及我可以在代码中更改哪些内容,以便它看起来像一个大的&#34;平面&#34;一套颜色?

2 个答案:

答案 0 :(得分:2)

接受的答案是正确的,但是如果你发现自己有类似的需要&#34; flatten&#34;你的收藏,你的回答是问题的标题。

更改您的方法以返回colors.flatten(),然后就可以获得所需内容。

http://docs.groovy-lang.org/latest/html/groovy-jdk/java/util/Collection.html#flatten%28%29

答案 1 :(得分:1)

您应该使用+,因为它会将其他集合元素添加到您的集合中,而<<会将整个集合添加为单个元素。

另请注意+不会改变列表,但会创建一个新列表。

Set<String> resolveAllColors(Set<String> colors) {
    if(colors.contains('Rainbow')) {
        colors + getAllRainbowColors()
    } else if(colors.contains('Red')) {
        colors + getAllRedishColors()
    }
}

Set<String> getAllRedishColors() {
    [
        'Rose',
        'Maroon'
    ]
}

Set<String> getAllRainbowColors() {
    allRedishColors + [
        'Orange',
        'Yellow',
        'Green',
        'Blue',
        'Indigo',
        'Violet'
    ]
}

试验:

Set<String> colors = [ 'White', 'Red' ]
assert resolveAllColors(colors) == [
    'White', 
    'Red',
    'Rose', 
    'Maroon', 
] as Set

assert allRainbowColors == [
        'Rose',
        'Maroon',
        'Orange',
        'Yellow',
        'Green',
        'Blue',
        'Indigo',
        'Violet'
] as Set
相关问题