I have this object ClientSearch
public class ClientSearch{
private Long clientNumber;
private String queueNumber;
private String clientName;
private String customerName;
.....
}
I need to sort this by this rule:
Show the clientNumber descending first then by customerName descending and after all records with clientNumber are displayed, sort by queueNumber in descending order and customerName in descending order.
This should be the result --- ClientNumber desc then, CustomerName desc, then, QueueNumber desc then, CustomerName desc
ClientNumber ClientName CustomerName
987654 Client1 Xyz1
987654 Client2 Abc2
555555 Client3 zzzzz1
21212 XYZ1 aaaab
111111 Client10 cZ
111111 Client11 cY
Z1Z1Z1 ClientX zzzzz
Z1Z1Z1 ClientY yyyyy
X2X2X2 Clienxyz aaaaaa
HHHHHH ClientH bbbbbb
AAAAAA ClientA xxxxxx
Basically each ClientSearch object has either a clientNumber or a queueNumber (if there is no client number then the queuNumber is considered a client number thats why it is displayed under that column),
what I thought of doing is, after I receive a List from my query (which I have no control, I just received the List<>), i will iterate through the list with the condition.
if clientNumber is present then add to a List<ClientSearch> withClientNumbers
else if queueNumber is present then add to a List<ClientSearch> withQueueNumbers
After doing this, I'll sort the withClientNumbers with a Comparator that compares the ClientSearch's clientNumber then if they are equal to zero ill do another compare with ClientSearch's customerName. I just need to multiply these with -1 to make sure it is DESC.
I'll do the same with queueNumbers but with a different comparator.
then Ill create a new List newList and then will do this
newList.addAll(withClientNumbers); //make sure this is first in the list
newList.addAll(queueNumbers); // so to satisfy the condition that queueNumbers are shown after a sorted clientNumbers.
Can you suggest any other elegant way to do this? I feel that my method is not the most optimized one. Take note that I'm using Java 1.6
humans.sort(Comparator.comparing(Human::getName).thenComparing(Human::getAge));See baeldung.com/java-8-sort-lambda for the full explanation