Reputation: 57
I have a string array in Java. I need to sort it by the number of character "a"s within the word (decreasing order). If some words contain same number of character a, then I need to sort those words by their lengths(decreasing order). And if the length is same, then alphabetically.
Example array:
["aaaasd","a","aab","aaaabcd","ef","cssssssd","fdz" ,"kf","zc","lklklklklklk","l"]
needs to be sorted like:
["aaaabcd","aaaasd","aab","a","lklklklklklk","cssss ssd","fdz","ef","kf","zc","l"]
Upvotes: 0
Views: 228
Reputation: 50716
This should do it:
// compare count of 'a' chars, descending
Comparator<String> comparator = Comparator.comparing(s -> s.chars().filter(c -> c == 'a').count(), Comparator.reverseOrder());
// then string length, descending
comparator = comparator.thenComparing(String::length, Comparator.reverseOrder());
// then natural (alphabetical) order
comparator = comparator.thenComparing(Comparator.naturalOrder());
// apply sort
Arrays.sort(strArr, comparator);
Upvotes: 2
Reputation: 17483
As it's already mentioned, just use Arrays.sort()
method with your own Comparator
:
Arrays.sort(arr, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (countA(o1) == countA(o2)) {
if (o1.length() == o2.length()) {
// Compare lexicographically
return o2.compareTo(o1);
}
// Compare by the length
return o2.length() - o1.length();
}
// Compare by the number of 'a'
return countA(o2) - countA(o1);
}
private int countA(String s) {
int total = 0;
for (int pos = 0; pos < s.length(); ++pos) {
if (s.charAt(pos) == 'a') {
total++;
}
}
return total;
}
});
Where arr
is your String
array.
The main idea is to check criterias according to their precedence and check new criteria only if objects are equal according to all previous criterias.
Upvotes: 2
Reputation: 6414
You could use a util method in Arrays
class:
public static <T> void sort(T[] a, Comparator<? super T> c)
Just write your own implementation of Comparator
and pass it as parameter along with the array of strings you wish to sort by it.
Upvotes: 1