javajava-collections-api

Convenience method to initialize mutable Set in Java


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


Solution

  • 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);