繁体   English   中英

如何过滤照片列表-Android?

[英]How to filter list of photos - android?

我正在尝试执行以下操作:按今天,本周,本月和今年的日期,对象值(日期类型)对数组进行排序,我知道如何使用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;
}

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

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());

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);
     }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM