Reputation: 11
I’m trying to sort through a String array of names. I have two different string arrays for first names and last names and I’m trying to sort through them in alphabetical order without using any kind of array sorting. Is there any kind of way to tell Java whether we want our String array going from increasing to decreasing order?
Upvotes: 1
Views: 80
Reputation: 27966
Generally classes extend Comparable
and implement compareTo
in order to designate a natural order for their objects. However you could write your own Comparator<String>
that performs a custom ordering.
Comparator<String> myOrder (s1, s2) -> ... calculate order ...
Arrays.sort(stringArray, myOrder);
Once you've defined a Comparator
you can reverse it with .reversed()
which would make you sort in descending rather than ascending order:
Arrays.sort(stringArray, myOrder.reversed());
Upvotes: 1