I want to sort an array of strings by whether they contain a custom pattern or not.
I have tried custom sort using comparator, but they all sort based on ascending or descending order. My requirement is as follows:
String[] strArr = { "maven", "maven_apache", "java", "multithreading", "java_stream" };
String patternToMatch = "java";
Then output should be a sorted array with strings containing the pattern java
first, followed by the others:
String[] strArr = { "java", "java_stream", "maven", "maven_apache", "multithreading" };
To sort an array of strings in Java, we can use Arrays. sort() function.
Using the toCharArray() method Get the required string. Convert the given string to a character array using the toCharArray() method. Sort the obtained array using the sort() method of the Arrays class. Convert the sorted array to String by passing it to the constructor of the String array.
As simple as defining a Comparator
and sorting the elements based on it:
Arrays.sort(strArr, Comparator.comparing(x -> !x.startsWith("java")));
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