【问题标题】:How to sort array object by specific string field?如何按特定字符串字段对数组对象进行排序?
【发布时间】:2015-03-28 16:21:48
【问题描述】:

这是我的对象的类(我需要时间戳是一个字符串):

public class Evento{
    public String timestamp;

    public Evento(String timestamp) {
        super();
        this.timestamp = timestamp;
    }
    public String getTimestamp() {
        return timestamp;
    }
}

在我的活动中,我有:

Evento evento = new Evento[10];
for(int i = 0; i<10; i++)
    evento[i] = new Evento(/*Casual String timestamp*/);

那么我已经填充了数组,如何按插入的时间戳对其进行排序?

【问题讨论】:

  • Arrays.sort()Comparator&lt;T&gt; 接口的自定义实现
  • 在 java 8 中,假设您想要对字符串值进行“自然”排序,您可以创建比较器,如:Comparator&lt;Evento&gt; comparator = Comparator.comparing(Evento::getTimestamp);docs.oracle.com/javase/8/docs/api/java/util/…

标签: java android


【解决方案1】:

如前所述,您将需要 Comparator 接口的自定义实现。由于是字符串,我先将时间戳转换为日期对象:Converting string timestamp to date,然后你可以按照这个例子按日期排序Sort objects in ArrayList by date?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-19
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 2014-07-10
    • 2020-05-24
    • 2015-03-11
    相关资源
    最近更新 更多