9

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,096
  • 3
  • 28
  • 44

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
  • 52,687
  • 11
  • 83
  • 118
8

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
  • 29,416
  • 12
  • 68
  • 88