Search code examples
javacomparable

How to make an arraylist of string sorted by the second character


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;


Solution

  • You need a Comparator, not Comparable. From Comparable:

    This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.

    From Comparator:

    A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural ordering.

    It can't be done with Comparable, because String implements 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 where Comparator comes into play (this is what it was designed for).

    public class Main {
    
      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, Comparator.comparingInt(s -> s.charAt(1)));
        System.out.println(arr);
        //prints [zav, abc, ace, cde, pgq, crf]
      }
    }
    

    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).