141

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 ?

2

11 Answers 11

118

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!

5
  • 3
    Now, whoever said that Java was too verbose? Of course this is the best answer! Oct 16, 2017 at 22:38
  • Thank's a lot @BobDoolittle ! Oct 17, 2017 at 13:48
  • 2
    For anyone using java 9+ please also see Holly's answer below: stackoverflow.com/a/48025159/229743
    – Taylor
    Jan 10, 2019 at 18:36
  • I still prefer use the Java 8 "Stream way" than the Java 9 feature, because "collectors" allow you to customize the resulting collection (may be "List", "Set" or any custom structure desired), while the utils of java 9 must be called separatedly for each collection type (and not all structures have an corresponding "util" ). Jan 15, 2019 at 14:08
  • 1
    flawless answer Mr. Anderson!
    – Gaurav
    May 25, 2020 at 18:47
68

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

6
  • Is there a non-immutable version of this?
    – cahen
    May 3, 2013 at 12:25
  • 3
    @cahen yes: Sets.newHashSet("a", "b") or Sets.newLinkedHashSet("a", "b") May 3, 2013 at 12:26
  • 1
    I added a mutable variant to the answer. May 3, 2013 at 12:32
  • actually, Sets.newLinkedHashSet() does not exist with that signature, sorry May 3, 2013 at 12:33
  • I was able to remove one of the type arguments: Set<String> mySet = ImmutableSet.of("a", "b");
    – joshden
    Jun 13, 2016 at 21:03
62

You could use

new HashSet<String>(Arrays.asList("a","b"));
1
  • I would rather do this then use the stream version. I can simply statically import "asList", making this even less verbose. Aug 18, 2020 at 19:15
29

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

4
28

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")
2
  • for these special cases, it is likely the best solution as it uses the standard java.util API
    – arcuri82
    Jan 26, 2016 at 11:16
  • 2
    java.util.Collections.emptySet() is, in my mind, preferred over EMPTY_SET, due to type safety. From the comments in the Collections class: Unlike the like-named field, this method is parameterized.
    – Eddified
    Apr 3, 2018 at 17:14
22

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.

2
  • 3
    This is the best answer so far, because it points out what Arrays.asList() actually does. Many devs seem to believe that Arrays.asList() creates a java.util.ArrayList, while it actually creates a java.util.Arrays$ArrayList (which is only partially mutable and a live view of the underlying array) May 3, 2013 at 12:36
  • 1
    As to why someone would want to do this, the most common reason to construct a Set (or List) by hand is in a test class where you are passing in test values. May 20, 2016 at 14:17
6

No but you can do it like this

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

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));
  }
1
  • 1
    I actually wrote this exact same solution--nice! Dec 3, 2021 at 4:30
3

In guava you could use

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

newHashSet

1

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

-1
List<String> myList = new ArrayList<String>(Arrays.asList("a", "b"));
myList.add("c");
System.out.println(myList);

It worked without error

1
  • This answer as is atm doesn't create a Set
    – cahen
    Jun 5 at 9:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.