我想要一种将 HashSet
的内容复制到集合中,同时不阻止新插入的方法。
BlockingQueue
在 drainTo
中具有此功能方法。
如何使用HashSet
来做到这一点?谢谢。
* 我愿意使用“并发 HashSet”结构,例如 ConcurrentHashMap.newKeySet()
。
最佳答案
像这样的方法怎么样:
public <T> int drainTo(Set<? extends T> source, Collection<T> target) {
Iterator<? extends T> it = source.iterator();
int count = 0;
while (it.hasNext()) {
target.add(it.next());
it.remove();
count++;
}
return count;
}
public static void main(String[] args) throws Exception {
Collection<String> list = new ArrayList<>();
// HashSet<String> set = new HashSet<>();
Set<String> set = ConcurrentHashMap.newKeySet();
set.add("1");
set.add("2");
set.add("3");
new Thread(() -> {
set.add("4");
set.add("5");
}).start();
drainTo(set, list);
// could print [1, 2, 3] , [1, 2, 3, 4], or [1, 2, 3, 4, 5]
// since there's no guarantee that the thread finished putting all elements in yet
System.out.println(list);
}
关于java - 在Java中是否有一个具有类似 `BlockingQueue.drainTo`功能的HashSet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53500610/