function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
:) :) :) :) :):) :) :) :) :) 

How to select random element from Set<String>

Set<String> setUserID = new Set<String>{'1','55','80','12', '6','22','87'};

 

Now I want to select random element from it.  Below random method is not yet exist. So how can I select random element from this set. Any other idea?

 

System.debug('Random Set Element  = ' +setUserID.random());

 

Best Answer chosen by Admin (Salesforce Developers) 
mroarkmroark

You really have two options. 

 

The first option is to generate a random index, convert the set to a list, and fetch the list element using the bracket notation.

 

Set<String> setArray = new Set<String> {'a', 'b', 'c'}; 
// Convert the Set to a list
List<String> lstArray = new List<String>();
lstArray.addAll(setArray);
//Generate a random list index
Double randomNumber = Math.random();
Integer arrayLength = lstArray.size());
Integer randomIndex = (randomNumber *(arrayLength-1)).intValue();
//Output the element at the list index generated above
System.debug('Random element: '+lstArray[randomIndex]);

 

The second option is to generate the random index, then iterate through the Set until you get to the appropriate element.

 

// Generate the set
Set<String> setArray = new Set<String> {'a', 'b', 'c'};
// Create a random index
Double randomNumber = Math.random();
Integer arraySize = setArray.size();
Integer randomIndex = (randomNumber *(arraySize-1)).intValue();
// Loop through the Set until you get to the element.
for (String str : setArray)
{
    if (randomIndex == 0)
    {
	System.debug('Random element: '+str);    
        break;
    }
    randomIndex--;
}

 

 

 

All Answers

ryanjuptonryanjupton

Ketan1248,

 

You can use our crypto or math classes to grab random numbers. Use that random number as an index for retrieval. Check here for more: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_restful_crypto.htm and here: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_math.htm.

sfdcfoxsfdcfox
Set<String> setUserID = new Set<String>{'1','55','80','12', '6','22','87'};
System.debug(LoggingLevel.Error,(new List<String>(setUserId))[Math.mod(Math.abs(Crypto.getRandomLong().intValue()),setUserId.size())]);

Convert to a list, then pull out a random element. 

mroarkmroark

You really have two options. 

 

The first option is to generate a random index, convert the set to a list, and fetch the list element using the bracket notation.

 

Set<String> setArray = new Set<String> {'a', 'b', 'c'}; 
// Convert the Set to a list
List<String> lstArray = new List<String>();
lstArray.addAll(setArray);
//Generate a random list index
Double randomNumber = Math.random();
Integer arrayLength = lstArray.size());
Integer randomIndex = (randomNumber *(arrayLength-1)).intValue();
//Output the element at the list index generated above
System.debug('Random element: '+lstArray[randomIndex]);

 

The second option is to generate the random index, then iterate through the Set until you get to the appropriate element.

 

// Generate the set
Set<String> setArray = new Set<String> {'a', 'b', 'c'};
// Create a random index
Double randomNumber = Math.random();
Integer arraySize = setArray.size();
Integer randomIndex = (randomNumber *(arraySize-1)).intValue();
// Loop through the Set until you get to the element.
for (String str : setArray)
{
    if (randomIndex == 0)
    {
	System.debug('Random element: '+str);    
        break;
    }
    randomIndex--;
}

 

 

 

This was selected as the best answer
willardwillard
List<id> mylist = new list<id>(myset);
Id randomid = mylist[math.random() * (mylist.size()-1)]
K.G.K.G.
Love that one-liner, @sfdcfox - thanks!