Sorting list with nulls as higher value

25 / Sep / 2012 by Bhagwat Kumar 2 comments

I had a list of Strings and wanted to sort them but pay special attention to null values. See the default sorting in demonstration :

List<String> animals=["Monkey", null, "Ape", null, "Tiger", "Lion"]

println animals.sort()              // [null, null, Ape, Lion, Monkey, Tiger]
println animals.sort().reverse()	// [Tiger, Monkey, Lion, Ape, null, null] 

You can see that nulls are lower in default groovy sorting.

What if we wanted to treat null as higher. In other words: Sort null values at the bottom in case of Ascending order and Sort null values at the top in case of Descending.

Apache commons-collections jar file contains a utility Comparator class : NullComparator. This class can be used to change the high/low interpretation of null values in sorting. Here is the sample code to see the NullComparator in action. (Note that this jar file is already included in grails library. Use grab to include this jar file when you are running code in groovy console).

@Grab(group='commons-collections', module='commons-collections', version='3.2.1')
import org.apache.commons.collections.comparators.NullComparator
// public NullComparator(boolean nullsAreHigh)

def nullHigh = new NullComparator(true) 
println animals.sort{a, b->, b)}  // [Ape, Lion, Monkey, Tiger, null, null]
println animals.sort{b, a->, b)}  // [null, null, Tiger, Monkey, Lion, Ape]

def nullLow = new NullComparator(false)
println animals.sort{a, b->, b)} // same as animals.sort()
println animals.sort{b, a->, b)} // same as animals.sort().reverse()

Useful Links :


comments (2)

  1. zelzylbym

    After research a few of the weblog posts on your web site now, and I truly like your manner of blogging. I bookmarked it to my bookmark web site listing and will likely be checking again soon. Pls try my website as well and let me know what you think.

  2. spray foam applicators wanted in ny

    In decades past, it was not something that the average person was overly concerned about.
    Lower Costs – Saving the planet is important, but saving
    some money is also a priority. Because, a rush job that
    is being done common used insulation performance is dramatically reduced.


Leave a comment -