Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In sort closure, how to get null value last?

Hello I am using Grails 2.1 and I have a little problem I can't find a good solution to. I am querying the database for some objects and it returns and sort it as expected with one exception, the null value is first.

Here is the code I may use to query the database:

Object.findAllByObjectTypeAndDateBetween(ObjectType.REGULAR, startDate, stopDate).sort {it.str}

Is there any way I can sort by the strings and getting all null values last instead of first? I am looking for a simple way, not like this: Grails/Hibernate: how to order by isnull(property) to get NULLs last?

Thanks.

like image 276
Ms01 Avatar asked Dec 20 '22 13:12

Ms01


1 Answers

You can do this:

objects.sort { a, b ->
  !a.str ? !b.str ? 0 : 1 : !b.str ? -1 : a.str <=> b.str
}

Expanded for explanation:

objects.sort { a, b ->
  if( !a.str ) {             // If a.str is null or empty
    if( !b.str ) {           // If b.str is null or empty 
      return 0               // They are the same
    }
    else {                   // a.str is empty or null, but b.str has value
      return 1               // b.str should come before a.str
    }
  else {                     // a.str has value
    if( !b.str ) {           // b.str is null or empty
      return -1              // b.str should come after a.str
    }
    else {                   // Both have value, 
      return a.str <=> b.str // Compare them 
    }
  }

This will put null strings and empty strings at the end of the list, and sort the rest alphabetically

If you want the empty strings at the head of the list (and the nulls at the tail), you'd need to explicitly check for null rather than relying on Groovy Truth:

objects.sort { a, b ->
  a.str == null ? b.str == null ? 0 : 1 : b.str == null ? -1 : a.str <=> b.str
}
like image 137
tim_yates Avatar answered Jan 10 '23 01:01

tim_yates