Reputation: 89
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" };
Upvotes: 6
Views: 1355
Reputation: 121078
As simple as defining a Comparator
and sorting the elements based on it:
Arrays.sort(strArr, Comparator.comparing(x -> !x.startsWith("java")));
Upvotes: 8
Reputation: 11
I think this can work for you. You can use it to determine if the string starts with "java", then swap it to the first know "non-java" of the array if it returns true.
public boolean startsWith(String prefix, int toffset)
Tests if the substring of this string beginning at the specified index starts with the specified prefix. Parameters: prefix - the prefix. toffset - where to begin looking in this string.
Returns: true if the character sequence represented by the argument is a prefix of the substring of this object starting at index toffset; false otherwise. The result is false if toffset is negative or greater than the length of this String object; otherwise the result is the same as the result of the expression
this.substring(toffset).startsWith(prefix)
Upvotes: 0