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);
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
source
share