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

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 ?


Solution 1:

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:

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:

You could use

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

Solution 4:

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:

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.)