【问题标题】:How to filter list of photos - android?如何过滤照片列表 - android?
【发布时间】:2017-01-10 21:01:36
【问题描述】:

我正在尝试这样做:按今天、本周、本月和今年对对象值数组(日期类型)进行排序,并且我知道如何使用 Comparator 类按降序或升序对日期数组进行排序,但我不知道如何像我说的那样对数组进行排序,到今天、本周、本月或今年。

private void sortTopicsByDate() {
    Collections.sort(topics, new Comparator<Topic>() {
        @Override
        public int compare(Topic o1, Topic o2) {
            return o1.getCreatedTime().compareTo(o2.getCreatedTime());
        }
    });
}

更新(包含今天创建的照片的过滤列表)

private List<Topic> getFilteredTopics() {
    List<Topic> filteredList = new ArrayList<>();
    Date now = new Date(); // today date
    Calendar cal = Calendar.getInstance();
    Calendar getCal = Calendar.getInstance();
    cal.setTime(now);
    int nYear  = cal.get(Calendar.YEAR);
    int nMonth = cal.get(Calendar.MONTH);
    int nDay   = cal.get(Calendar.DAY_OF_MONTH);

    if (topics != null) {
        for (Topic topic : topics) {
            getCal.setTime(topic.getCreatedTime());
            int year  = getCal.get(Calendar.YEAR);
            int month = getCal.get(Calendar.MONTH);
            int day   = getCal.get(Calendar.DAY_OF_MONTH);
            if (nDay == day && month == nMonth) {
                filteredList.add(topic);
            }
        }
    }
    return filteredList;
}

【问题讨论】:

  • 什么是“这个”?
  • 显示你到目前为止尝试过的内容
  • “按今天、本周、本月或今年排序”是什么意思?你能在你的问题中添加一个具体的例子吗?
  • 你当前的代码有什么问题?
  • 你的意思是你想filter你的照片?

标签: java android arrays sorting


【解决方案1】:

使用 java 8,您可以使用streaming-api按日期过滤您的主题。 请注意,此解决方案不包括start 中的startfinish,如果您希望您必须修改filter 中的条件。

Collection<Topic> topics = ...;
Date start = ...;
Date finish = ...;
List<Topic> filteredTopics = topics.stream()
    .filter(t -> t.getCreatedTime().after(start) && t.getCreatedTime().before(finish))
    .collect(Collectors.toList());

【讨论】:

  • 为什么不t.getCreatedTime.after(start) &amp;&amp; t.getCreatedTime.before(finish)
  • @bradimus 您的建议显然要好得多 :-) 我更正了我的答案
  • 我应该如何初始化 Collection?
  • 这与您用于排序的Collection 相同,例如可以是List
  • 好的,知道了。我会让你知道结果。
【解决方案2】:

Date 已经实现了Comparable 接口,具有自然升序的日期顺序(即首先是年,然后是月,然后是月中的某天)。听起来您是在逆序(即今天,然后是昨天,然后是上周等)之后。如果是这种情况,您可以使用反向比较:

Comparator<Date> reverseComparator = new Comparator<Date>(){
     @Override public int compare(Date d1, Date d2){
         //dealing with nulls ignored for purposes of explanation
         return -1*d1.compareTo(d2);
     }
}

这应该首先对最近的日期进行排序。

【讨论】:

  • 另一种方法是使用Collections.reverseOrder()
  • @JohnLeehey 绝对是,而且通常也更推荐:) 在这种情况下我选择不这样做,因为我认为这更能说明该方法。
  • OP 说 “我知道如何按降序或升序对日期数组进行排序”,那么您为什么要回答(不好!)降序示例?不好,我的意思是如果compareTo() 恰好返回Integer.MIN_VALUE,你的代码将会失败。要颠倒顺序,只需翻转d1d2,如return d2.compareTo(d1);。无论如何,你没有回答这个问题,所以:-1(没用).
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-25
  • 1970-01-01
相关资源
最近更新 更多