Delete duplicates from collection

I want to get a list of all languages ​​that have a different language, where the ISO3 code is used to identify the Locale language. I thought the following should work

class ISO3LangComparator implements Comparator<Locale> {

    int compare(Locale locale1, Locale locale2) {
        locale1.ISO3Language <=> locale2.ISO3Language
    }
}

def allLocales = Locale.getAvailableLocales().toList()
def uniqueLocales = allLocales.unique {new ISO3LangComparator()}

// Test how many locales there are with iso3 code 'ara'
def arabicLocaleCount = uniqueLocales.findAll {it.ISO3Language == 'ara'}.size()

// This assertion fails
assert arabicLocaleCount <= 1
+3
source share
2 answers

You are using the wrong syntax: you are using Collection.unique (Closing closure) :

allLocales.unique {new ISO3LangComparator()}

You should use Collection.unique (comparator comparator)

allLocales.unique (new ISO3LangComparator())

So just use ()instead {}, and your problem is resolved.

+5
source

what Adam said.
or...

allLocales.unique{it.ISO3Language}

and you forgot about the comparator

+4
source

All Articles