How to sort ArrayList <Object> in android ascending

I have a requirement to sort ArrayList<Object>(custom objects) in ascending order by name. For this, I use the comparator method as

My ArrayList:

ArrayList<Model> modelList = new ArrayList<Model>();

The code I'm using is:

   Comparator<Model> comparator = new Comparator<Model>() {
            @Override
            public int compare(CarsModel lhs, CarsModel rhs) {

                String  left = lhs.getName();
                String right = rhs.getName();

                return left.compareTo(right);

            }
        };

   ArrayList<Model> sortedModel = Collections.sort(modelList,comparator);

//While I try to fetch the sorted ArrayList, I am getting error message 

I am completely stuck and really do not know how to proceed further to sort the list ArrayList<Object>. Please help me with this. Any help and solutions would be helpful to me. I am posting my exact script for your reference. Thanks in advance.

Example:

ArrayList<Model> modelList = new ArrayList<Model>();
modelList.add(new Model("chandru"));
modelList.add(new Model("mani"));
modelList.add(new Model("vivek"));
modelList.add(new Model("david"));

Regular list:

for(Model mod : modelList){
  Log.i("names", mod.getName());
}

Exit:

chandru
mani
vivek
david

My requirement after sorting:

for(Model mod : modelList){
  Log.i("names", mod.getName());
}

Exit:

chandru
david
mani
vivek
+4
source share
2 answers

. Comparator , ( ):

ArrayList<Model> modelList = new ArrayList<>();
modelList.add(new Model("chandru"));
modelList.add(new Model("mani"));
modelList.add(new Model("vivek"));
modelList.add(new Model("david"));

Collections.sort(modelList, new Comparator<Model>() {
    @Override
    public int compare(Model lhs, Model rhs) {
        return lhs.getName().compareTo(rhs.getName());
    }
});

:

chandru
david
mani
vivek
+27
 Collections.sort(actorsList, new Comparator<Actors>() {
      @Override
      public int compare(Actors lhs, Actors rhs) {
       return lhs.getName().compareTo(rhs.getName());
     }
    });
+1

All Articles