Best Way to Sort a List of Resources ?

Avatar

Avatar

CQDarren

Avatar

CQDarren

CQDarren

15-10-2015

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

Accepted Solutions (1)

Accepted Solutions (1)

Avatar

Avatar

Ryan_Lunka

Avatar

Ryan_Lunka

Ryan_Lunka

15-10-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.

Answers (0)