6

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" };
2
  • There are some syntax errors in this Java code. Are you sure this is the input and the expected output? Commented Feb 12, 2019 at 14:26
  • @LutzHorn Corrected Commented Feb 12, 2019 at 14:29

2 Answers 2

8

As simple as defining a Comparator and sorting the elements based on it:

Arrays.sort(strArr, Comparator.comparing(x -> !x.startsWith("java")));
Sign up to request clarification or add additional context in comments.

11 Comments

@Eugene Thanks , this helped, exactly what I wanted!
@tobias_k false < true for boolean (or Boolean) variables, so if the word x starts with "java", x.startsWith("java") would return true, thus moving the words that start with "java" to the end. That's why you need to negate the predicate, and that's why I find this code not very expressive (though it is very short and elegant).
@FedericoPeraltaSchaffner agreed, takes a bit of fiddling to actually get it; but I got used to it
@Prasann Well, you could still slap on thenComparing(Comparator.naturalOrder())
@Holger Absolutely agree, just wanted to make my point clear. I'm not advocating to not use advanced features, but to make it clear for code readers and reviewers what the code does instead. And when code is not expressive enough, a comment is always appreciated.
|
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.