Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort an array of Strings that contain "m" first, everything else second

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Many thanks for any suggestions!

>Solution :

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 to chain 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 an explicit in the lambda expression, like shown above (String s) -> ..., or use so-called type-witness <String, Boolean>comparing(...).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading