How can I make Cartesian product with Java 8 streams?

后端 未结 9 756
谎友^
谎友^ 2020-11-28 08:10

I have the following collection type:

Map> map;

I would like to create unique combinations of each o

9条回答
  •  渐次进展
    2020-11-28 08:47

    Use a Consumer Function Class, a List and a foreach

        public void tester(){
    
            String[] strs1 = {"2","4","9"};
            String[] strs2 = {"9","0","5"};
    
            //Final output is {"29", "49, 99", "20", "40", "90", "25", "45", "95"}
            List result = new ArrayList<>();
            Consumer consumer = (String str) -> result.addAll(Arrays.stream(strs1).map(s -> s+str).collect(Collectors.toList()));
            Arrays.stream(strs2).forEach(consumer);
    
            System.out.println(result);
    
    }
    

提交回复
热议问题