I want to sort an arrayList of String to be sorted by the second character and using the comparable interface and CompareTo method.
public class Main implements Comparable<String>{
public static void main(String[] args){
ArrayList<String> arr = new ArrayList<>();
arr.add("abc");
arr.add("cde");
arr.add("ace");
arr.add("crf");
arr.add("pgq");
arr.add("zav");
Collections.sort(arr);
}
@Override
public int compareTo(String temp){
what should I write here;
}
}
I'm expecting the results as:
zav, abc, ace, cde, pqq, crf;
You need a Comparator, not Comparable. From
Comparable:From
Comparator:It can't be done with
Comparable, becauseStringimplements it, meaning its natural ordering is already defined and you can't change it. That's why you need to define custom comparison strategy and that's whereComparatorcomes into play (this is what it was designed for).Keep in mind, this does not take into account the possibility of the strings having less than 2 characters (if the constraints allow such input, you need to handle it in the implementation).