Your achievements

Level 1

0% to

Level 2

Tip /
Sign in

Sign in to Community

to gain points, level up, and earn exciting badges like the new
Bedrock Mission!

Learn more

View all

Sign in to view all badges

SOLVED

Best Way to Sort a List of Resources ?

Avatar

Level 2

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

1 Accepted Solution

Avatar

Correct answer by
Level 5

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.

View solution in original post

0 Replies

Avatar

Correct answer by
Level 5

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.