Home > database >  Is it possible to create custom java comparator which will compare by two different object propertie
Is it possible to create custom java comparator which will compare by two different object propertie

Time:08-20

Could you please help me to figure out how to implement comparator which will have the following algorithm?

Let's imagine we have class Order which have properties CollectionDT and OrderingDT.

What it's needed to sort list with Order objects by CollectionDT descending and if CollectionDT is null for some object passed to comparator then sort by OrderingDT.

The example and required output:

Order1: CollectionDT - 2022-08-17, OrderingDT - 2022-08-17 
Order2: CollectionDT - null, OrderingDT - 2022-08-18
Order3: CollectionDT - 2022-08-19, OrderingDT 2022-08-19

Needed output:

Order3
Order2
Order1

CodePudding user response:

Comparator has all you want. It could be something like this, though I doubt the correctness.

List<Order> orders = ...
orders.sort(Comparator.nullsFirst(Order::getCollectionDT)
                      .reversed()
                      .thenComparing(Order::getOrderingDT));

This would do CollectionDT sorted descendingly, the nulls at the end (nullsFirst reversed), and equal CollectionDTs sorted by OrderingDT.

They must implement Comparable<CollectionDT> resp. Comparable<OrderingDT>.

It looks like you want something intertwined. Then using a simple basic Comparator on compareTo. More readable.

Comparator<Order> orderComparator = (lhs, rhs) ->
    lhs.getCollectionDT() == null
        ? rhs.getCollectionDT() != null ? 1
        : lhs.getOrderingDT().compareTo(rhs.getOrderingDT())
        : rhs.getCollection() == null ? -1
        : lhs.getCollectionDT().compareTo(rhs.getCollectionDT());
 orders.sort(orderComparator);

CodePudding user response:

I have taken the time to code a demonstration of an answer in Eiffel for anyone who would like to see. You can find that video here. You can look at the code directly from Github.

The primary goal of the demo is to show that objects in Eiffel can be taught how to compare themselves among themselves—such that—when you place them into a list, they auto-sort themselves by the code-rules you provide. This means you can also have descendant child classes that know how to sort themselves along with more generic parents in the same list, so you don't have to create lists of just one type of object.

You can even teach different objects that are otherwise unrelated how to organize themselves in the list, as long as they have some kind of loose inheritance. The Eiffel way of doing this is quite powerful!

I invite you to watch the video, examine the code on Github, download EiffelStudio (free GPL version) and play with the code directly! If you need help, reach out to me. I am happy to assist you in any way I can!

  • Related