在并行流的谓词函数中有效使用最终HashSet是否安全?
如果没有,那么使用什么是好的数据结构?我没有看到ConcurrentSet ……我想我可以使用ConcurrentHashMap.entrySet().
从我能够收集的内容来看,即使未修改HashSet,最新状态也可能在所有线程中都不可用.但也许有一个简单的技巧可以使它可用?
List<Integer> items = Stream
.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
.collect(Collectors.toList());
Set<Integer> exclude = Stream
.of(5, 10, 15)
.collect(Collectors.toSet());
List<Integer> filtered = items
.parallelStream()
.filter(num -> !exclude.contains(num))
.collect(Collectors.toList());
最佳答案 只要您不修改并行线程中的集合,使用您的示例描述的方式应该是完全安全的.