When as Set is not what you want

When you want to filter out duplicates in a list in groovy you normally do something like:

        def list = [2, 1, 2, 3]
        def filtered = list as Set
        assertEquals([1, 2, 3], filtered as List)

This kicks out all duplicates in a one-liner. But what if the list is sorted (e.g. in reverseOrder)?

        def list = [3, 2, 2, 1]
        def filtered = list as Set
        assertEquals([3, 2, 1], filtered as List) // this fails!

One solution would be to use a small closure:

        def list = [3, 2, 2, 1]
        def filteredList = []
        list.each {
            if (!filteredList.contains(it)) {
                filteredList << it
            }
        }
        assertEquals([3, 2, 1], filteredList)

This closures preserves the order and filters out the duplicates.

2 thoughts on “When as Set is not what you want

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s