Hello, I need to sort a list of items by their prices. Sorting criteria is like this; - When sortin...
n
Hello, I need to sort a list of items by their prices. Sorting criteria is like this; • When sorting low to high, negative values need to always be before positive ones. The highest negative value being at the top and the highest green value being at the bottom • When sorting high to low, vice versa However, some items may have null price. Let’s say there is a negative trending item with null price so then all negative values that have non-null price need to come first before those that have null price. However, I can’t make it work in no way. I am using
nullsLast
with combination of
compareBy
but it is not working. Do you know what’s wrong? I tried;
Copy code
sortedWith(nullsLast(compareBy { it.price }))
1
Actual position of null priced item should be like this
r
Hey Nuh! Is this what you need?
Copy code
val collection = listOf(10, null, 2, -1, -3, null, -2, 1)

val sorted = collection
    .sortedBy { it }
    .groupBy {
        when {
            it == null -> 1
            it < 0 -> 0
            else -> 2
        }
    }
    .toSortedMap()
    .flatMap { it.value }
output: [-3, -2, -1, null, null, 1, 2, 10]
n
Hey Rafael! Thank you it works. We can’t achieve this using
nullsLast
and so on right? If so, is this a performant way, wdyt?
r
Well, as the name says, it will push the nulls to the end of the collection so there's no application for you. The implementation I shared should be ok in terms of performance because it just sorts, splits, and merges the results in the right order, so no big deal.
n
Thanks for explaining! It is working like a charm!
Hey Rafael, it’s me again. I found a bug in your code. Looks like you don’t take performance type into account. Let’s say I have one negative null value and one positive null value. In that case, each of them should be at the bottom of respective group. Negative null value should be at the bottom of negative values and positive null value should be at the bottom of positive values
r
Hey Nuh, can you share an example of negative and positive null value?
😅 1
n
Let’s say I have such a set of numbers;
20.30, 45.12, -13.67, null(positive one), null(negative one), -9.45
If I sort from low to high(ascending) output should be;
-13.67, -9.45, null(negative one), 20.30, 45.12, null(positive one)
if in descending order;
45.12, 20.30, null(positive one), -9.45, -13.67, null(negative one)
r
Well, I've never seen a negative/positive null value 😅. Clearly you gotta adapt the snippet to your code, but should be easy to do so by changing the groupBy method