Does .asSet(...) exist in any API?

JavaCollections

Java Problem Overview


I'm looking for a very simple way to create a Set.

Arrays.asList("a", "b" ...) creates a List<String>

Is there anything similar for Set ?

Java Solutions


Solution 1 - Java

Now with Java 8 you can do this without need of third-party framework:

Set<String> set = Stream.of("a","b","c").collect(Collectors.toSet());

See Collectors.

Enjoy!

Solution 2 - Java

Using Guava, it is as simple as that:

Set<String> mySet = ImmutableSet.<String> of("a", "b");

Or for a mutable set:

Set<String> mySet = Sets.newHashSet("a", "b")

For more data types see the Guava user guide

Solution 3 - Java

You could use

new HashSet<String>(Arrays.asList("a","b"));

Solution 4 - Java

For the special cases of sets with zero or one members, you can use:

java.util.Collections.EMPTY_SET

and:

java.util.Collections.singleton("A")

Solution 5 - Java

In Java 9, similar function has been added via factory methods:

Set<String> oneLinerSet = Set.of("a", "b", ...);

(There are equivalents for List as well.)

Solution 6 - Java

As others have said, use:

new HashSet<String>(Arrays.asList("a","b"));

The reason this does not exist in Java is that Arrays.asList returns a fixed sized list, in other words:

public static void main(String a[])
{
  List<String> myList = Arrays.asList("a", "b");
  myList.add("c");
}

Returns:

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractList.add(Unknown Source)
	at java.util.AbstractList.add(Unknown Source)

There is no JDK implementation of a "fixed-size" Set inside the Arrays class. Why do you want this? A Set guarantees that there are no duplicates, but if you are typing them out by hand, you shouldn't need that functionality... and List has more methods. Both interfaces extend Collection and Iterable.


As others have said, use guava If you really want this functionality - since it's not in the JDK. Look at their answers (in particular Michael Schmeißer's answer) for information on that.

Solution 7 - Java

Here's a little method you can use

  /**
   * Utility method analogous to {@link java.util.Arrays#asList(Object[])}
   *
   * @param ts
   * @param <T>
   * @return the set of all the parameters given.
   */
  @SafeVarargs
  @SuppressWarnings("varargs")
  public static <T> Set<T> asSet(T... ts) {
    return new HashSet<>(Arrays.asList(ts));
  }

Solution 8 - Java

No but you can do it like this

new HashSet<String>(Arrays.asList("a", "b", ...));

Solution 9 - Java

In guava you could use

Set<String> set = Sets.newHashSet("a","b","c");

newHashSet

Solution 10 - Java

Another way to do it using Java 8 and enums would be:

Set<String> set = EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.READ);

See EnumSet.

I would recommend a performance analysis between this approach and

Set<String> set = Stream.of(StandardOpenOption.CREATE, StandardOpenOption.READ).collect(Collectors.toSet());

because if you have more than five elements the javadoc of the method states that may be performance issues as you can see in the javadoc of Set.Of(E, E...).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncahenView Question on Stackoverflow
Solution 1 - JavaMr. AndersonView Answer on Stackoverflow
Solution 2 - JavaMichael SchmeißerView Answer on Stackoverflow
Solution 3 - JavaDev BlankedView Answer on Stackoverflow
Solution 4 - JavaSamuel Edwin WardView Answer on Stackoverflow
Solution 5 - JavaHolly CumminsView Answer on Stackoverflow
Solution 6 - Javadurron597View Answer on Stackoverflow
Solution 7 - JavaStuart ClarkView Answer on Stackoverflow
Solution 8 - JavaEvgeniy DorofeevView Answer on Stackoverflow
Solution 9 - JavaOscarRyzView Answer on Stackoverflow
Solution 10 - JavaPhilippe GioseffiView Answer on Stackoverflow