-1

How would I convert a List, (let's say an ArrayList) to a ConcurrentSet in Java?

I'm aware of this answer: Easiest way to convert a List to a Set in Java But I can't seem to get it to work for a ConcurrentSet.

Community
  • 1
  • 1
orrymr
  • 2,264
  • 4
  • 21
  • 29
  • 1
    what you mean by `ConcurrentSet`? there is one JDK implementation of thread-safe `Set` -- [`ConcurrentSkipListSet`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentSkipListSet.html), so you can easily use its `Collection`-arg constructor. – Alex Salauyou Apr 22 '16 at 11:30
  • I've tried: Set set = new ConcurrentSet(myList); I see now that ConcurrentSet isn't part of the JDK, and is part of another library I have downloaded. I guess this is why I'm getting downvoted so harshly :P – orrymr Apr 22 '16 at 11:41

2 Answers2

2

You can do a conversion like this.

public static <E> Set<E> toConcurrentSet(Collection<E> coll) {
    Set<E> set = Collections.newSetFromMap(new ConcurrentHashMap<>());
    set.addAll(coll);
    return set;
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

If with ConcurrentSet you mean a set that can be accessed concurrently, you can try:

Set<Foo> foo = Collections.synchronizedSet(new HashSet<Foo>(myList));

The returned set will be thread safe.

mdewit
  • 2,016
  • 13
  • 31