【问题标题】:Groovy: Duplicate values displayed multiple timesGroovy:重复值显示多次
【发布时间】:2017-07-10 21:27:38
【问题描述】:

我正在尝试通过 groovy 从 txt 文件中检索和显示重复值,当我使用以下代码 sn-p 时,我能够检索到我需要的所有值及其重复值;但是,当显示输出时,它会显示出现两次以上的任何值两次以上,而不仅仅是一次。我附加了输出以更好地可视化我遇到的情况。任何指导表示赞赏!

 //Find and display duplicate values
    Set<String> store = new HashSet<>()
    for (String num : phones){
        if (!store.add(num)){
            println("Duplicate Number: " + num + " : " + phones.count(num) + " instances")
    }
    }

Output:

Duplicate Number: 567-567-5678 : 3 instances
Duplicate Number: 877-898-8767 : 4 instances
Duplicate Number: 877-898-8767 : 4 instances
Duplicate Number: 789-987-7890 : 2 instances
Duplicate Number: 567-567-5678 : 3 instances
Duplicate Number: 456-567-8907 : 2 instances
Duplicate Number: 877-898-8767 : 4 instances

【问题讨论】:

    标签: groovy duplicates hashset


    【解决方案1】:

    只有在第一次添加时才能打印出来:

    Set<String> store = new HashSet<>()
    for (String num : phones){
        def count = phones.count(num)
        if (store.add(num) && count > 1) {
            println("Duplicate Number: " + num + " : " + count + " instances")
        }
    }
    

    对于 Groovy,它实际上是一个单行:

    phones.countBy { it }.findAll { it.value > 1 }.each { k, v -> println "Dup: $k: $v times" }
    

    【讨论】:

    • 知道了!感谢您的澄清!
    猜你喜欢
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    • 2012-06-28
    • 1970-01-01
    • 2012-11-08
    相关资源
    最近更新 更多