Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #118 List to set

Create the set y from the list x.
x may contain duplicates. y is unordered and has no repeated values.

Turning the list [a,b,c,b] into the set {c,a,b}
import java.util.LinkedHashSet;
import java.util.Set;
Set<T> y = new LinkedHashSet<>(x);

The `LinkedHashSet` will preserve the order of x.
import static java.util.stream.Collectors.toSet;
import java.util.Set;
Set<T> y = x.stream().collect(toSet());
import java.util.Set;
import java.util.HashSet;
Set<T> y = new HashSet<T>(x);

x is a Collection<T>, e.g. a List<T>.
Elements of x and y have the same type T.
import static java.util.Set.copyOf;
import java.util.Set;
Set<T> y = copyOf(x);

Immutable
import java.util.HashSet;
import java.util.List;
Set<T> y = new HashSet<>(x);

T is the type of the elements.
(def y (set x))

New implementation...
< >
programming-idioms.org