如何筛选照片列表 – android?
我正在尝试这样做:按今天日期,本周,本月和今年对对象数组(日期类型)进行排序,我知道如何使用Comparator类按降序或升序排序日期数组,但我不知道如何我知道如何按今天的日期,本周,本月或今年排序数组。
private void sortTopicsByDate() { Collections.sort(topics, new Comparator() { @Override public int compare(Topic o1, Topic o2) { return o1.getCreatedTime().compareTo(o2.getCreatedTime()); } }); }
更新(过滤列表,其中包含今天创建的照片)
private List getFilteredTopics() { List 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
中的start
和finish
。
Collection topics = ...; Date start = ...; Date finish = ...; List filteredTopics = topics.stream() .filter(t -> t.getCreatedTime().after(start) && t.getCreatedTime().before(finish)) .collect(Collectors.toList());
Date
已经实现了Comparable
接口,具有自然升序的日期顺序(即年份首先,然后是月份,然后是月份日期)。 听起来你是在逆序(即今天,然后是昨天,然后是上周等)。如果是这种情况,你可以使用反向比较:
Comparator reverseComparator = new Comparator (){ @Override public int compare(Date d1, Date d2){ //dealing with nulls ignored for purposes of explanation return -1*d1.compareTo(d2); } }
这应该先排序更近的日期。