例:给定数组[1,2,3]和数组[4,5],想要返回结果:[ [1,4] , [1,5] , [2,4] , [2,5] , [3,4] , [3,5] ] 。
List<Integer> num1 = Arrays.asList(1,2,3);
List<Integer> num2 = Arrays.asList(4,5);
// ① map()方式
List<Stream<int[]>> collect =
num1.stream()
.map(i -> num2.stream()
.map(j -> new int[]{i, j})
)
.collect(Collectors.toList());
//打印结果
List<List<String>> collect1 =
collect.stream()
.map(i -> i.map(Arrays::toString)
.collect(Collectors.toList())
)
.collect(Collectors.toList());
System.out.println(collect1);
//[[[1, 4], [1, 5]], [[2, 4], [2, 5]], [[3, 4], [3, 5]]]
System.out.println("===================");
// ② flatMap()方式
List<int[]> collect2 =
num1.stream()
.flatMap(i -> num2.stream()
.map(j -> new int[]{i, j})
)
.collect(Collectors.toList());
//打印结果
List<String> collect3 =
collect2.stream()
.map(Arrays::toString)
.collect(Collectors.toList());
System.out.println(collect3);
//[[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]
备注:
map() 方式返回的是List<Stream<int[]>>
flatMap() 方式返回的是List<int[]>