Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Sort a List of strings, determining the order depending on the contains of the string

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.

like image 729
Marcel Avatar asked Sep 13 '25 16:09

Marcel


1 Answers

In java 8 you can create Comparators 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
like image 151
fabian Avatar answered Sep 16 '25 05:09

fabian