我正在开发基于Java的CMS OpenCms。我有一个List集合,我在其中存储CMSResources,我从类别中获取:
CmsObject cmso = cms.getCmsObject();
// Get the category service instance
CmsCategoryService cs = CmsCategoryService.getInstance();
// Get resources assigned a specific category. (You could also provide a CmsResourceFilter here.)
List<CmsResource> categoryResourcesNewBies = cs.readCategoryResources(cmso, "newbies/", true,"/");
现在,我已经编写了一些代码来对它进行排序:
final SimpleDateFormat outputFormat = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss zzz");
final Comparator<CmsResource> CREATE_ORDER = new Comparator<CmsResource>() {
public int compare(CmsResource one, CmsResource another) {
String oneCreated = "";
String anotherCreated = "";
try {
oneCreated = outputFormat.format(new Date(one.getDateCreated()));
anotherCreated = outputFormat.format(new Date(another.getDateCreated()));
} catch (Exception e) {
oneCreated = "";
anotherCreated = "";
}
return oneCreated.compareTo(anotherCreated);
}
};
Collections.sort(categoryResourcesNewBies,CREATE_ORDER);
当我使用Iterator遍历集合时,订单不正确。它应该根据日期,升序或降序进行排序,因为我正在尝试使用比较器。
我已经迭代使用:
Iterator<CmsResource> inew = categoryResourcesNewBies.iterator();
while (inew.hasNext()) {
CmsResource r = inew.next();
// Here, you could check the file type ID and/or file extension, and do something
// based on that info. For example, you could group PDF and DOC files separately, or
// discard all files other than PDFs, and so on.
String urinew = cmso.getSitePath(r);
<li class="margin-bottom-10 left-nav-list"><a href="<%= cms.link(urinew) %>" target="_blank"><%= cms.property(CmsPropertyDefinition.PROPERTY_TITLE, urinew, urinew) %><img src="/.content/flexiblecontents/img/new.gif" alt = "New"/> <%out.println(outputFormat.format(r.getDateCreated()));%></a></li>
}
请有人帮助我。
答案 0 :(得分:1)
尝试这个,它应该解决你的问题:
final Comparator<CmsResource> CREATE_ORDER = new Comparator<CmsResource>() {
public int compare(CmsResource one, CmsResource another) {
Date oneCreated = null;
Date anotherCreated = null;
try {
oneCreated = new Date(one.getDateCreated());
anotherCreated = new Date(another.getDateCreated());
} catch (Exception e) {
oneCreated = null;
anotherCreated = null;
return 0;
}
if ( oneCreated.after(anotherCreated))
return 1;
else if ( oneCreated.before(anotherCreated))
return -1;
else
return 0;
}
};
Collections.sort(categoryResourcesNewBies,CREATE_ORDER);
答案 1 :(得分:0)
为什么需要创建日期对象?
cmsResource.getDateCreated()返回一个long,你可以将它与Long.compare(x,y)进行比较:
我建议这个更短的解决方案:
public int compare(CmsResource one, CmsResource another) {
try {
return Long.compare(one.getDateCreated(),another.getDateCreated());
} catch (Exception e) {
return 0;
}
}