javacollectionsxpagesssjs

How to use Collections.shuffle() to shuffle an ArrayList in SSJS?


I need to shuffle/randomize the contents of an ArrayList. I was excited to discover Collections.shuffle() but unlike other Java maps/lists/collections it appears the Collections class is not direclty available to my XPages SSJS code. Is there a way to import/reference the Collections class for access to its shuffle() method?

Here is my current code:

var numbersArrayList = new java.util.ArrayList;
for (i=1; i<=10; i++) {
    numbersArrayList.add(i)
}
dBar.dump(numbersArrayList);

Collections.shuffle(numbersArrayList);

dBar.dump(numbersArrayList);

And here is the error indicating the Collections class cannot be found:

This file is encoded using UTF-8. Please set your editor/viewer options appropriately
10/29/20 6:22 AM: Exception Thrown
Context Path: /TravelTrackPaul2.nsf
Page Name: /resetData.xsp
Control id: button6
Property: onclick
Script interpreter error, line=8, col=13: [ReferenceError] 'Collections' not found
     6: 
     7: Collections.shuffle(numbersArrayList);
->   8: 
     9: dBar.dump(numbersArrayList);

Solution

  • Call the method using the complete package name:

    java.util.Collections.shuffle(numbersArrayList);