Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array of String based on a name pattern

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" };
like image 363
Karan mehta Avatar asked Feb 12 '19 14:02

Karan mehta


People also ask

How do you sort an array of strings?

To sort an array of strings in Java, we can use Arrays. sort() function.

How do you sort an array of strings alphabetically in Java?

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.


1 Answers

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

Arrays.sort(strArr, Comparator.comparing(x -> !x.startsWith("java")));
like image 194
Eugene Avatar answered Oct 22 '22 02:10

Eugene