Example:
Our list contains 5 names: Kevin, Hans, Fritz, Han Solo, Peter
And I now want to have all the names that contain "Han" at the top.
So the sorted list would look like that:
Hans, Han Solo, Kevin, Fritz, Peter
What I have tried so far:
Nothing because i have no clue, but i already googled and didn't find anything.
Deleting/adding items from/to the list is not an option becaue i am using the list in a CheckListView
(ControlsFX component) where each item has a checked state which would get lost.
In java 8 you can create Comparator
s based on a function applied to the element. Also there are methods to reverse the order produced by a comparator and chain comparators.
This allows a relatively simple creation of a comparator using the existence of a substring as primary sort criterion and the String
sorting as secondary criterion. Note that depending on your requirements the second part (.thenComparing(Comparator.naturalOrder())
) may not be necessary:
final String part = "Han";
Comparator<String> comparator = Comparator.<String, Boolean>comparing(s -> s.contains(part)).reversed()
.thenComparing(Comparator.naturalOrder());
The result of sorting your items with this Comparator
is
Han Solo, Hans, Fritz, Kevin, Peter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With