Best Way to Sort a List of Resources ? | Community
Skip to main content
October 16, 2015
Solved

Best Way to Sort a List of Resources ?

  • October 16, 2015
  • 1 reply
  • 2860 views

Hi everyone,

As you all probably know im new to CQ.

 

I have been looking over the APIs, and was wondering what the best solution is to sort a list of Resources.

My current snippet is :

Iterator<Resource> myResources = res.listChildren(); while (myResources.hasNext()) { Resource resource = myResources.next(); String name = resource.getName(); LOGGER.info("The node found is = " + name); }

 

So what I need to do is sort the resources by name before I loop?  Do I need a custom comparator for this or is there something in the CQ APIs that will do the job? 

 

I.e it would be nice to use Collections.sort etc...

Thanks

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

I would use Collections.sort() and a custom comparator that sorts based on the Resource name (or whatever sorting logic you want). It wouldn't be appropriate, in my opinion, for Sling to sort those resources for you. It should be returning that list of resources in their natural order within the repository. This order may be the result of the order in which they were added, most recent at the bottom. They may have a specific order, as do some nodes in the JCR if their parent specifies that they are orderable. 

An alternative is that you could perform a JCR query, which I'm pretty sure would allow you to order the results. This would probably be a poorly performant way to go for what you're doing, however.

I'm not sure why you need to sort a list or Resource objects, but be aware that at an application level, that natural order may have specific meaning.

1 reply

Accepted solution
October 16, 2015

I would use Collections.sort() and a custom comparator that sorts based on the Resource name (or whatever sorting logic you want). It wouldn't be appropriate, in my opinion, for Sling to sort those resources for you. It should be returning that list of resources in their natural order within the repository. This order may be the result of the order in which they were added, most recent at the bottom. They may have a specific order, as do some nodes in the JCR if their parent specifies that they are orderable. 

An alternative is that you could perform a JCR query, which I'm pretty sure would allow you to order the results. This would probably be a poorly performant way to go for what you're doing, however.

I'm not sure why you need to sort a list or Resource objects, but be aware that at an application level, that natural order may have specific meaning.