Sorting list with nulls as higher value
I had a list of Strings and wanted to sort them but pay special attention to null values. See the default sorting in demonstration :
[groovy]
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]
[/groovy]
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).
[groovy]
@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-> nullHigh.compare(a, b)} // [Ape, Lion, Monkey, Tiger, null, null]
println animals.sort{b, a-> nullHigh.compare(a, b)} // [null, null, Tiger, Monkey, Lion, Ape]
def nullLow = new NullComparator(false)
println animals.sort{a, b-> nullLow.compare(a, b)} // same as animals.sort()
println animals.sort{b, a-> nullLow.compare(a, b)} // same as animals.sort().reverse()
[/groovy]
Useful Links :
http://mvnrepository.com/artifact/commons-collections/commons-collections/3.2.1
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.
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.