I have a requirement to sort ArrayList<Object>
(Custom objects) in Ascending order based upon name. For that purpose I am using comparator method as like
我需要根据名称按升序排序ArrayList
My ArrayList :
我的ArrayList:
ArrayList<Model> modelList = new ArrayList<Model>();
ArrayList
Code I am using:
我正在使用的代码:
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 up and really dont know how to proceed further in order to get sorted list of ArrayList<Object>
. Please help me with this. Any help and solutions would be helpful for me. I am posting my exact scenario for your reference. Thanks in advance.
我完全陷入困境,真的不知道如何继续进行以获得ArrayList
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"));
Normal List:
正常清单:
for(Model mod : modelList){
Log.i("names", mod.getName());
}
Output :
输出:
chandru
mani
vivek
david
My requirement after sorting to be like:
排序后我的要求如下:
for(Model mod : modelList){
Log.i("names", mod.getName());
}
Output :
输出:
chandru
david
mani
vivek
2 个解决方案
#1
28
Your approach was right. Make your Comparator
inner like in the following example (or you can create a new class instead):
你的方法是对的。在下面的示例中使您的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());
}
});
output:
输出:
chandru
david
mani
vivek
#2
3
Collections.sort(actorsList, new Comparator<Actors>() {
@Override
public int compare(Actors lhs, Actors rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
#1
28
Your approach was right. Make your Comparator
inner like in the following example (or you can create a new class instead):
你的方法是对的。在下面的示例中使您的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());
}
});
output:
输出:
chandru
david
mani
vivek
#2
3
Collections.sort(actorsList, new Comparator<Actors>() {
@Override
public int compare(Actors lhs, Actors rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});