sorting collections | Community
Skip to main content
Dterner
New Participant
October 16, 2015
Solved

sorting collections

  • October 16, 2015
  • 1 reply
  • 838 views

Hi, I have the following code, it is supposed to sort my array list by the date property in reverse chronological order. It is doing some sort since the items listed are not in their natural order when the sort is run. I can't figure out what it's sorting by but it is certainly not by date. Any ideas on where I went wrong?

 

List<Page> childPages = new ArrayList<Page>(); Iterator<Page> articleChildren = articleRoot.listChildren(new PageFilter(request)); while(articleChildren.hasNext()) { childPages.add(articleChildren.next()); } Date now = new java.util.Date(); Collections.sort(childPages, Collections.reverseOrder(new Comparator<Page>() { public int compare(Page o1, Page o2) { Date oNow = new java.util.Date(); Date o1Created = o1.getProperties().get("jcr:created", oNow); Date o1Date = o1.getProperties().get("date", o1Created); Date o2Created = o2.getProperties().get("jcr:created", oNow); Date o2Date = o2.getProperties().get("date", o2Created); return o1Date.compareTo(o2Date); } }));

Thanks,

Dmitry

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by smacdonald2008

does it sort by order when you use this code:

 

  1. Collections.sort(childPages, Collections.sort(new Comparator<Page>() {
  2. public int compare(Page o1, Page o2) {
  3. Date oNow = new java.util.Date();
  4. Date o1Created = o1.getProperties().get("jcr:created", oNow);
  5. Date o1Date = o1.getProperties().get("date", o1Created);
  6. Date o2Created = o2.getProperties().get("jcr:created", oNow);
  7. Date o2Date = o2.getProperties().get("date", o2Created);
  8. return o1Date.compareTo(o2Date);
  9. }

 

Take a look at this Stackoverflow thread that talks about a similar issue:

 

http://stackoverflow.com/questions/7197548/how-to-sort-a-collection-by-a-date-field

1 reply

smacdonald2008
smacdonald2008Accepted solution
New Participant
October 16, 2015

does it sort by order when you use this code:

 

  1. Collections.sort(childPages, Collections.sort(new Comparator<Page>() {
  2. public int compare(Page o1, Page o2) {
  3. Date oNow = new java.util.Date();
  4. Date o1Created = o1.getProperties().get("jcr:created", oNow);
  5. Date o1Date = o1.getProperties().get("date", o1Created);
  6. Date o2Created = o2.getProperties().get("jcr:created", oNow);
  7. Date o2Date = o2.getProperties().get("date", o2Created);
  8. return o1Date.compareTo(o2Date);
  9. }

 

Take a look at this Stackoverflow thread that talks about a similar issue:

 

http://stackoverflow.com/questions/7197548/how-to-sort-a-collection-by-a-date-field