How do I generate a Cartesian product in Java?

前端 未结 5 1093
予麋鹿
予麋鹿 2020-12-16 19:13

I have a number of ArrayList with each ArrayList having objects and each one can have different length. I need to generate permutation like in the

5条回答
  •  半阙折子戏
    2020-12-16 20:05

    With Java8 streams

        List a = Arrays.asList("a", "b", "c");
        List b = Arrays.asList("d", "e");
        String[][] AB = a.stream().flatMap(ai -> b.stream().map(bi -> new String[] { ai, bi })).toArray(String[][]::new);
        System.out.println(Arrays.deepToString(AB));
    

    output

        [[a, d], [a, e], [b, d], [b, e], [c, d], [c, e]]
    

    To get as List

        List> ll = a.stream().flatMap(ai -> b.stream().map(bi -> new ArrayList<>(Arrays.asList(ai, bi)))).collect(Collectors.toList());
    

提交回复
热议问题