我有一个包含 4 个成员的 java 对象列表。
int id;
String name;
String age;
int order;
我想根据名称对这个对象的列表进行排序
最佳答案
要么像这样实现一个Comparator
:
public static void main(String[] args) throws IOException {
List<MyObject> list = new ArrayList<MyObject>();
// add your objects to the list
Collections.sort(list, new Comparator<MyObject>() {
@Override
public int compare(MyObject o1, MyObject o2) {
return o1.name.compareTo(o2.name);
}
});
}
或者你可以在MyObject
上实现Comparable
接口(interface):
class MyObject implements Comparable<MyObject> {
int id;
String name;
String age;
int order;
@Override
public int compareTo(MyObject o) {
return name.compareTo(o.name);
}
}
public static void main(String[] args) throws IOException {
....
Collections.sort(list); // with the comparable interface
}
关于java - 将对象 w.r.t 列表排序为特定成员/状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7103490/