0

I am trying to sort Car by three values: first by type, then within the "type" bucket I want to sort those by price (lowest to highest), then if there are any that have the same price, I want to sort by age (newest to oldest).

However, some Cars have a null price. In these cases, I want all the null values to be at the end of the list.

I am trying to use Comparator.nullsFirst and Comparator.nullsLast, but neither of these are doing anything. I end up getting all the nulls first (regardless of which one I use), then the items sorted on price. I am wondering if it is because I have .reverse() which is negating the nullsFirst/Last?

Here is what I am trying:

cars.stream().sorted(Comparator.comparingInt((Car car) -> car.getCarMetadata().getCarType().getPriority())
     .thenComparing((Car car -> car.getCarMetadata().getPrice(), Comparator.nullsLast(Double::compareTo)).reversed()
     .thenComparing((Car car) -> car.getAge).reversed()).collect(Collectors.toList());

Any ideas on this?

1 Answer 1

1

Just figured it out.. Moving the reversed() inside the comparison ended up working, like so:

cars.stream().sorted(Comparator.comparingInt((Car car) -> car.getCarMetadata().getCarType().getPriority())
     .thenComparing((Car car -> car.getCarMetadata().getPrice(), Comparator.nullsLast(Double::compareTo)).reversed()
     .thenComparing((Car car) -> car.getAge).reversed()).collect(Collectors.toList());

I'm not sure I totally understand why this fixed it though.

Sign up to request clarification or add additional context in comments.

1 Comment

I don't see the difference between the two code pieces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.