Home > Back-end >  How to sort an array of Strings that contain "m" first, everything else second
How to sort an array of Strings that contain "m" first, everything else second

Time:10-24

String[] strArray = {"xyz", "aaazzz","abc","mft","gh","j", "aaazaz", "mm", "am"};

Arrays.sort(strArray, Comparator.comparing((s) -> s.contains("m")));
System.out.println("Array sorted by 'm': "   Arrays.toString(strArray));

I have been able to get the array so that it is sorted using 'm', but the results are in defending order - as in all strings that contain 'm' are at the end.

My print out reads;

Array sorted by 'm': [xyz, aaazzz, abc, gh, j, aaazaz, mft, mm, am]

I have considered using indexOf() but I haven't been able to figure out a way to get this to work.

Many thanks for any suggestions!

CodePudding user response:

The natural order of boolean values is false -> true (i.e. false comes first).

You need to change the condition of your Comparator to get elements containing m to be placed and the beginning of the sorted list:

Comparator.comparing(s -> !s.contains("m"))

You might want both groups of string (with and without m) to be sorted as well. For that you can use method thenComparing() which allow to build an aggregate Comparator based on several conditions:

Comparator.comparing((String s) -> !s.contains("m"))
    .thenComparing(Comparator.naturalOrder());

Note that when comparators are being chained together, the type inference mechanism fails to infer the types of arguments used in the chained methods based on the target type (i.e. the expected aggregate Comparator). And we need to either provide the types of argument in the lambda expression explicitly, like shown above (String s) -> ..., or use a so-called type-witness <String, Boolean>comparing(...).

  • Related