虽然@OldCurmudgeon 有一个很好的基本方法,但在更严肃的代码中,您可能想要制作一个Callable
对密钥进行昂贵处理并返回一个新的Collection
. 这可以与 Executor 和/或 CompletionService 结合使用。最后,您甚至不需要并发集合。
例如,如果键是字符串
public class DoesExpensiveProcessing implements Callable<Set<String>> {
final Set<String> inKeys;
public DoesExpensiveProcessing(Set<String> keys) {
this.inKeys = keys; // make a defensive copy if required...
}
public Set<String> call() {
// do expensive processing on inKeys and returns a Set of Strings
}
}
此时您甚至不需要并行集合
List<DoesExpensiveProcessing> doInParallel = new ArrayList<DoesExpensiveProcessing>();
for (Map map : maps) {
doInParallel.add(new DoesExpensiveProcessing(map.keySet()));
}
Set theResultingSet = new HashSet<String>();
List<Future<Set<String>>> futures = someExecutorService.invokeAll(doInParallel);
for (Future<Set<String>> f : futures) {
theResultingSet.addAll(f.get());
}