Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convenience method to initialize mutable Set in Java [duplicate]

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

like image 409
Rian Schmits Avatar asked May 12 '15 14:05

Rian Schmits


2 Answers

Guava is defintely a good solution.

Alternatively, you can do:

Set<T> mySet = new HashSet<>(Arrays.asList(t1, t2, t3));
like image 198
Jean Logeart Avatar answered Oct 23 '22 11:10

Jean Logeart


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);
like image 30
Joe Avatar answered Oct 23 '22 13:10

Joe