So I'm trying to sort a String Array using a Comparator but the sorting is based on the length of String then on the third Character of the String.
This is my Comparator so far:
class StringSorter implements Comparator<String> {
public int compare(String s1, String s2) {
if(s1.length() < s2.length()) {
return -1;
}
if(s1.length() > s2.length()) {
return 1;
}
return s1.charAt(3)+"".compareTo(s2.charAt(3)+"");
}
}//Comparator
This line return s1.charAt(3)+"".compareTo(s2.charAt(3)+""); is my attempt so far and I get an IndexOutOfBoundsException but every String in my Array has at least the length of 4 so I don't understand why the error.
As for my question, why do I get that error? and is that how I should write my Comparator if I'm to sort based on length and a character in the String?
Edit: The Arrays I need to process follows this format
{"1:bbbbb", "2:aaa", "=:ccc", "1:qqqq", "1:eeee", "=:zzz", "1:vvv", "2:oooo", "=:eee", "1:fffff"}
compareToget called on""or ons1.charAt(3)+""? Interesting order precedence thing here, maybe.Comparator<String> c = Comparator.comparingInt(String::length).thenComparingInt(s -> s.charAt(3));.