Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove duplicates from collection

I want to get a list of all Locales that have a different language, where the ISO3 code is used to identify the language of a Locale. 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
like image 455
Dónal Avatar asked Jun 26 '26 17:06

Dónal


1 Answers

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

allLocales.unique {new ISO3LangComparator()}

You should use Collection.unique(Comparator comparator)

allLocales.unique (new ISO3LangComparator())

So simply use () instead of {}, and your problem is solved.

like image 130
Adam Avatar answered Jun 29 '26 09:06

Adam