//现在有一个集合,里面有一些数据,想 两两对比 ,获取组合方式
List<Integer> mcnId = new ArrayList<>();
mcnId.add(1);
mcnId.add(2);
mcnId.add(3);
mcnId.add(4);
mcnId.add(5);
//方式一:
List<String> combinations = new ArrayList<>();
// 使用两层循环遍历生成所有的组合
for (int i = 0; i < mcnId.size(); i++) {
for (int j = i + 1; j < mcnId.size(); j++) {
int id1 = mcnId.get(i);
int id2 = mcnId.get(j);
String combination = id1 + "" + id2; // 可根据需要调整组合的格式
combinations.add(combination);
}
}
//方式二:
// 生成所有可能的 对(组合)
List<List<Integer>> pairs = IntStream.range(0, mcnId.size())
.boxed()
.flatMap(i -> IntStream.range(i + 1, mcnId.size())
.mapToObj(j -> Arrays.asList(mcnId.get(i), mcnId.get(j))))
.collect(Collectors.toList());
for (List<Integer> combination : pairs) {
System.out.println(combination.toString());
}
输出:
[1, 2]
[1, 3]
[1, 4]
[1, 5]
[2, 3]
[2, 4]
[2, 5]
[3, 4]
[3, 5]
[4, 5]
// 使用ForkJoinPool并行处理这些对
ForkJoinPool forkJoinPool = new ForkJoinPool();
forkJoinPool.submit(() -> pairs.parallelStream()
.forEach(pair -> {
Integer 1a = pair.get(0);
Integer 2b = pair.get(1);
// ... 其他处理逻辑 ...
})).get(); // 注意:这里使用了get()来等待任务完成,这可能会阻塞主线程。在实际应用中,你可能需要更好地管理异步任务。
//如果你处理的逻辑仅仅是进行某种计算或操作(如插入数据库),并且你不需要等待这些操作全部完成后再继续执行其他任务,那么你不应该使用get()来阻塞等待结果。get()方法会阻塞调用线程,直到任务完成。
3853

被折叠的 条评论
为什么被折叠?



