java - 将对象 w.r.t 列表排序为特定成员/状态

标签 java string list sorting

我有一个包含 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/

相关文章:

java - 开关盒顺序会影响速度吗?

Python:替换未知数量的字符串变量

linux - copy_to_user 在链表 linux 内核模块中不起作用

python - 修复索引错误 : List out of range issues

java - 创建新的子类实例

java - JdbcRowSetImpl 无法解析为类型?

java - Spring WS WSDL自动暴露: xsd import are not followed

c# - 编写正则表达式以搜索子字符串 C#

c - 如何使用for循环打印输入的字符串?

python - 执行 'if list in list' python 的正确方法