2

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>{
    'A','B','C','D'
};

List<String> endResult = new List<String>{
    'A','A;B','A;C','A;D','A;B;C','A;B;D','A;C;D','A;B;C;D',
    'B','B;C','B;D','B;C;D',
    'C','C;D',
    'D'
};

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

3
  • 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

0
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(); 
            newSubset.add(item); 
            
            // add the newly created set to the list of all subsets 
            newSubsets.add(newSubset); 
        }
        
        // add all the newly created subsets to the powerset 
        powerSet.addAll(newSubsets); 
    }
    
    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 .