I am trying to sort users based on their initials, and when initials are repeated, say 'Alex Fay' and 'Alba Finn', I have to sort them based on their age in descending order.
This is my current code:
List<SortedUser> sortedUserList = list.stream()
.sorted((a, b) -> {
int first = a.getName().charAt(0) + a.getLastName().charAt(0);
int second = b.getName().charAt(0) + b.getLastName().charAt(0);
if(first > second) {
return -1;
} if(first < second) {
return 1;
}
return b.getAge() - a.getAge();
}).collect(Collectors.toList());
The problem with this code is that when I have initials 'AR' and 'EN', their sums are the same (147) - therefore first == second, and they appear one after the other in incorrect order.
I also tried to compare the first name initial and the last name initial separately, but I still couldn't get it to work.
What can I change in order to sort them the way I want it?
Sample input:
(name=Alexandre, lastName=Wuckert, age=66),
(name=Allan, lastName=Wehner, age=84),
(name=Bradley, lastName=Thompson, age=78),
(name=Bernice, lastName=Schoen, age=63)
Sample output:
(name=Bradley, lastName=Thompson, age=78),
(name=Bernice, lastName=Schoen, age=63),
(name=Allan, lastName=Wehner, age=84),
(name=Alexandre, lastName=Wuckert, age=66)