I'm trying to randomize a list of search results returned from a query using APEX on the Salesforce platform. The closest language to APEX is Java so I added this to the Java topic in hopes a java expert could help. Right now, the same results are returned in the same order when using a specific search algorithm. It returns the list in the same order every time and the user sees the first series of records in the UI. I want to randomize that list so the first series of records will be different each time the user searches using the same search algorithm.
I created a method to return a random integer based on the lower and upper bounds of the search results list:
public static Integer getRandomInt (Integer lower, Integer upper)
return (Integer) (Math.floor(Math.random() * (upper - lower)) + lower);
I'm stuck on how I can set each element in the list with the random integer as the index until all elements have been set and I don't want any indexes to repeat. So, if I return 100 results back, as I iterate of the list, a random integer is generated, the index of that list element is set with that integer value within the upper and lower bounds, then the next iteration occurs, checks if the next integer has not already been used and then sets the index for the next list element. This continues until all list elements have been set. If I'm thinking the logic thru correctly, I should have a completely random list of search results.
How can I accomplish this using the Salesforce APEX language? Is there a better way to do this? Salesforce does not have a method to randomize a list or keyword to return a soql query in a random order, so the only way I can think to do this is using the math functions and create a new list and randomly setting each element index.
Any help is greatly appreciated.