我有一个模型类列表,其中有一个名为priority(String)的变量,列表中的每个项共享3个公共优先级(HIGH,LOW,MEDIUM)。我的问题是,我想使用其items priority(String)对列表进行排序。例如。所有HIGH优先级应该移到顶部,MEDIUM到中间,LOW到最后。提前谢谢。
public class Main extends Activity {
private ArrayList<Model> listOfModel = new ArrayList<>();
private void setData(){
listOfModel.addAll(getDataFromServer());
Collections.sort(listOfModel); //sort using priority
}
}
public class Model {
private String name;
private String score;
private String priority;//HIGH,MEDIUM,LOW
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
}
答案 0 :(得分:1)
创建一个自定义比较器,按顺序排列递增的优先顺序,即LOW,MEDIUM,HIGH
Collections.sort(listOfModel, new Comparator<Model>() {
@Override
public int compare(Model m1, Model m2) {
String p1 = m1.getPriority();
String p2 = m2.getPriority();
if(p1 == null) return 1;
if(p2 == null) return -1;
if(p1.equals(p2)) return 0;
if(p1.equals("LOW") && (p2.equals("MEDIUM") || p2.equals("HIGH")))
return -1;
if(p1.equals("MEDIUM") && p2.equals("HIGH"))
return -1;
return 1;
}
});
答案 1 :(得分:0)
您可以使用以下代码对自定义对象进行排序
Collections.sort(listOfModel, new Comparator<Model>(){
public int compare(Model m1, Model m2) {
return m1.getPriority().compareToIgnoreCase(m2.getPriority());
}
});
答案 2 :(得分:0)
试试这个:
item = "priority";
mSortAttributes(item, listOfModel );
public void mSortAttributes(final String item, ArrayList<Model> sortList ){
Collections.sort(sortList, new Comparator<Model>() {
@Override
public int compare(Model lhs, Model rhs) {
int retVal = 0;
//Ascending Order
if (item.equals("name")) {
retVal = lhs.name.compareToIgnoreCase(rhs.name);
} else if (item.equals(" score")) {
retVal = lhs.score.compareToIgnoreCase(rhs.score);
} else if (item.equals("priority")) {
retVal = lhs.priority.compareToIgnoreCase(rhs.priority);
}
return retVal;
}
});
}
答案 3 :(得分:0)
使用此Code.this工作正常
static class myComparater implements Comparator<Model> {
@Override
public int compare(Model o1, Model o2) {
String p1 = o1.getPriority();
String p2 = o2.getPriority();
if (p1.equals(p2)) {
return 0;
}
if (p1.equals("HIGH") && (p2.equals("MEDIUM") || p2.equals("LOW"))) {
return -1;
}
if (p1.equals("MEDIUM") && p2.equals("LOW")) {
return -1;
}
return 1;
}
}
答案 4 :(得分:0)
这正在工作。使用此代码,您可以添加更多的大小写。
private static Comparator<OrderHistoryItemData> COMPARE_BY_PAYMENT = new Comparator<OrderHistoryItemData>() {
private int map(String str) {
switch (str) {
case "HIGH":
return 0;
case "MEDIUM":
return 1;
case "LOW":
return 2;
default:
return 3;
}
}
@Override
public int compare(String o1, String o2) {
return map(o1) - map(o2 );
}
};