7

Is there a convenience method to initialize a Set equivalent to Collections.singleton, which returns a mutable Set instead of an immutable one?

Rian Schmits
  • 3,018
  • 2
  • 27
  • 43

2 Answers2

11

Guava is defintely a good solution.

Alternatively, you can do:

Set<T> mySet = new HashSet<>(Arrays.asList(t1, t2, t3));
Jean Logeart
  • 50,693
  • 11
  • 81
  • 116
9

Guava's Sets includes:

public static <E> HashSet<E> newHashSet(E... elements)

which:

Creates a mutable HashSet instance containing the given elements in unspecified order.

You can call it with a single item as:

Sets.newHashSet(item);
Joe
  • 26,561
  • 11
  • 64
  • 84