javajava-8setcombinationskey-generator

Generate all possible keys for 2 or more sets of strings in same order


There are N sets with M values in each. How to generate all possible combination in given order of sets efficiently?.

SetA = {'A', 'B'}
SetB = {'x', 'Y'}
SetC = {'L', 'M'}

Key Order = SetA_SetB_SetC

Output :

A_X_L, A_X_M, A_Y_L, A_Y_M, B_X_L, B_X_M, B_Y_L, B_Y_M

Solution

  • From Java-8 onwards use #Stream API, I have implemented the code below:

    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    
    
    public class CandidateCode {
    
        public static void main(String[] args) {
            List<String> ListA = Arrays.asList("A", "B");
            List<String> ListX = Arrays.asList("X", "Y");
            List<String> ListL = Arrays.asList("L", "M");
            List<String> collect = ListA.stream().flatMap(a -> ListX.stream().flatMap(x -> ListL.stream().map(l -> a + "_" + x + "_" + l))).collect(Collectors.toList());
            collect.forEach(System.out::println);
        }
    }
    

    Output:

    A_X_L
    A_X_M
    A_Y_L
    A_Y_M
    B_X_L
    B_X_M
    B_Y_L
    B_Y_M