【问题标题】:Ordering a list by an attribute of the elements按元素的属性对列表进行排序
【发布时间】:2016-01-26 08:00:16
【问题描述】:

我有一个 java 数组列表:

List<Log> logs = new ArrayList<Log>();

日志类具有以下属性:

String type;
int num;
Date date;

按日期排序日志列表的好方法是什么?

【问题讨论】:

标签: java list sorting arraylist


【解决方案1】:

您可以如下实现Comparator 接口:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
public class Main {
    public static void main(String arg[]) {
        List<Log> logs = new ArrayList<Log>();
        logs.sort(new CustomComparator());
    }
}

class CustomComparator implements Comparator<Log> {
    @Override
    public int compare(Log o1, Log o2) {
        return o1.date.compareTo(o2.date);
    }
}

class Log {
    String type;
    int num;
    Date date;
}

请注意使用sort函数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多