I am writing a Comparator with which I can sort a String array using character count. The Strings are all lowercase ASCII characters.
Eg.
input = {"art", "bash", "tar"};
Expected sorted output = {"art", "tar", "bash"};
Here, it does not matter if "bash" is at the beginning, but "art" and "tar" should be one after the other, in no particular order as they have matching character count.
I have this code, where I am using a simple array to check and keep the character count and compare.
Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(String s1, String s2){
if (s1.equals(s2)) return 0;
int[] a1 = getCountArray(s1);
int[] a2 = getCountArray(s2);
if (Arrays.equals(a1, a2)) return 0; // character count matches
return s1.compareTo(s2);
}
private int[] getCountArray(String s) {
int[] array = new int[256];
for (int i=0; i<s.length(); i++){
array[s.charAt(i) - 'a'] ++;
}
return array;
}
};
String[] input = {"art", "bash", "tar"};
Arrays.sort(input, comparator);
However, it does not work. What am I doing wrong?
artandtarequal, but for some reason you placedbashbetween them which is unclear to me.). In your second if condition there is a missingsinArrays.Arrays.comparemethod and use it like@Override public int compare(String s1, String s2){ return Arrays.compare(getCountArray(s1), getCountArray(s2)); }. If that does not give you results which you ware expecting then please point out difference between expected and actual result.s.charAt(i) - 'a'atarray[s.charAt(i) - 'a']? Since your array has256length why you want to shift value of index? If you will try to shift character which position is smaller than'a'then you will end up with negative index.Shifting would make sense if you are sure that you are dealing only with characters in rangea-zbut for them you don't need array of length 256 (since there are less characters in a-z range).