查找和修改集合

时间:2016-02-19 05:02:00

标签: groovy

我需要查找和修改集合中的重复条目。

我可以执行以下操作,但这需要几个步骤。

是否有更简洁的方法来实现最终输出,指示所有具有重复项的条目?

void "test find and mark duplicate entries"() {
    given:
    def sports = ["baseball", "basketball", "football", "basketball", "basketball", "football", "soccer", "volleyball"]

    when:
    def duplicateEntries = sports.findAll { sports.count(it) > 1 }.unique()

    then:
    duplicateEntries == ["basketball", "football"]

    when:
    sports = sports.collect {
        if (duplicateEntries.contains(it)) {
            return it + "-dupe"
        } else {
            return it
        }
    }

    then:
    sports == ["baseball", "basketball-dupe", "football-dupe", "basketball-dupe", "basketball-dupe", "football-dupe", "soccer", "volleyball"]
}

3 个答案:

答案 0 :(得分:3)

与其他答案相同的复杂性,只是更高的内存效率; - )

def sports = ["baseball", "basketball", "football", "basketball", "basketball", "football", "soccer", "volleyball"]
sports.collect { sports.count(it) > 1  ? "$it-dupe" : it }

答案 1 :(得分:2)

下面的代码可能会稍微短一点,但我不希望奇迹在这里;)

def sports = ["baseball", "basketball", "football", "basketball", "basketball", "football", "soccer", "volleyball"]
def duplicates = sports.countBy { it }.findAll { it.value > 1 }.keySet()
sports.collect { it in duplicates ? "$it-dupe" : it }

答案 2 :(得分:2)

从@Opal扩展答案。这个使用groupBy ..

def sports = ["baseball", "basketball", "football", "basketball", "basketball", "football", "soccer", "volleyball"]
def groupBy=sports.groupBy ().collect { it.value.size()>1  ? "$it.key-dupe" : "$it.key" }
println( groupBy)