gpt4 book ai didi

java - 无法在 OpenCms 中按升序或降序对列表集合进行排序

转载 作者:行者123 更新时间:2023-12-01 12:06:12 26 4
gpt4 key购买 nike

我正在开发 OpenCms,这是一个基于 Java 的 CMS。我有一个列表集合,其中存储了我从以下类别获得的 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<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>
}

请有人帮助我。

最佳答案

试试这个,它应该可以解决您的问题:

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

关于java - 无法在 OpenCms 中按升序或降序对列表集合进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27577191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com