(My specific case was to do with processing an optional parameter when handling a HTTP request)Ĭonsider this as an example: fun foo(x: Long = 1) If you liked the post, you can share it and can subscribe to this blog for more such posts.I recently encountered a scenario where I wanted to be able to provide a nullable type argument to a function where the corresponding parameter was non-nullable with a default value. – When the specified comparator is null, then the returned comparator consider all non null values to be equal. ![]() – When both are non null, the specified comparator, which is passed to nullsFirst method as parameter, is used to determined the sort order Returns a null-friendly comparator that considers null to be less than non null. When we have list of elements where few elements are null and we want these nulls to be treated as the smallest elements in the list, we can use nullsFirst method of Comparator interface, which does following : – When both objects are null, they are considered equal.Įmployee Įmployee Summary – Returns a null-friendly comparator that considers null to be less than non null. NullsFirst is one of the static method defined in the Comparator interface having following signature : In Java 8, there has been addition of lots of default and static methods in Comparator interface. What is nullsFirst method doing in Comparator? ![]() So if you want to sort ,say your list.You can create a class implementing Comparator interface’s compare method, wherein you can define the logic of sorting and pass this comparator to the list.sort() method and it will then sort according to your defined logic.Īlternatively, rather than creating a separate class implementing Comparator interface, you can pass lambda function(implementing compare method of Comparator) to list.sort() method. Comparator is a FunctionalInterface which has following abstract method
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |