I have a list of strings which I need to put together in every valid combination so that the result can be used in an includes WHERE clause of a multi-select picklist in a SOQL query. Basically, I need to go from myList to endResult:

List<String> myList = new List<String>{

List<String> endResult = new List<String>{

I've written so many fruitless loops that I broke down and decided to post here. Thanks in advance!

  • 5
    Why do you need to create all the permutations? Why not just use includes ('A', 'B', 'C', 'D')? What specific scenario are you trying to address?
    – Phil W
    Commented Jan 28, 2023 at 20:03
  • @PhilW Hm, I so rarely use Multi-Select Picklists that I suspect I overthought this... I'm going to go with your suggestion and see if there are any issues. (I think I would only need the permutations if both the input list and the matching list were both multi-select picklists). In any case, thanks!
    – Mike
    Commented Jan 28, 2023 at 20:22
  • Even if the input list was a multiselect picklist, you'd just end up having a list of selected values, and includes would still work as you expect.
    – sfdcfox
    Commented Jan 29, 2023 at 3:10

1 Answer 1

public static List<List<String>> getPowerSet(List<String> input) {
    List<List<String>> powerSet = new List<List<String>>();
    powerSet.add(new List<String>()); // add empty set
    for (String item : input) {
        List<List<String>> newSubsets = new List<List<String>>();
        for (List<String> subset : powerSet) {
            // create a new subset from the existing subset and add the current element to it
            List<String> newSubset = subset.clone(); 
            // add the newly created set to the list of all subsets 
        // add all the newly created subsets to the powerset 
    return powerSet; 

enter image description here

I believe your question has already been answered in the comments above. However, the permutation that you were looking for is a power set and in my opinion retrieving that would be a very time complex operation with upper-bound of O(2^n).

In case you still want to use it I have added the code snippet above.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .