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 ?

cahen
  • 15,807
  • 13
  • 47
  • 78

11 Answers11

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!

Mr. Anderson
  • 1,465
  • 1
  • 14
  • 15
  • 3
    Now, whoever said that Java was too verbose? Of course this is the best answer! – BobDoolittle Oct 16 '17 at 22:38
  • Thank's a lot @BobDoolittle ! – Mr. Anderson Oct 17 '17 at 13:48
  • 2
    For anyone using java 9+ please also see Holly's answer below: https://stackoverflow.com/a/48025159/229743 – Taylor Jan 10 '19 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" ). – Mr. Anderson Jan 15 '19 at 14:08
  • 1
    flawless answer Mr. Anderson! – Gaurav May 25 '20 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

Michael Schmeißer
  • 3,407
  • 1
  • 19
  • 32
62

You could use

new HashSet<String>(Arrays.asList("a","b"));
Dev Blanked
  • 8,555
  • 3
  • 26
  • 32
  • I would rather do this then use the stream version. I can simply statically import "asList", making this even less verbose. – Marcio Lucca Aug 18 '20 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.)

Holly Cummins
  • 10,767
  • 3
  • 23
  • 25
  • I tried this and got a compiler warning that this is not an API method. – Philippe Gioseffi Jun 21 '18 at 15:57
  • Here's the relevant java doc: https://docs.oracle.com/javase/9/docs/api/java/util/Set.html. As well as using a Java 9+ JDK, you may need to adjust your IDE or build tool to use Java 9 compliance (for example, for maven, it would be similar steps to those here, but set to 1.9: https://stackoverflow.com/questions/16798066/set-default-java-compliance-level-for-maven-projects-in-eclipse) – Holly Cummins Jun 25 '18 at 09:30
  • 1
    Wish we could use Java 9.. We're living in the past! :( – wheeleruniverse Feb 26 '19 at 18:03
  • that is good but have some restrictions on the size of the arguments... – Radoslav Ivanov Oct 22 '19 at 00:37
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")
Samuel Edwin Ward
  • 6,526
  • 3
  • 34
  • 62
  • for these special cases, it is likely the best solution as it uses the standard java.util API – arcuri82 Jan 26 '16 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 03 '18 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.

durron597
  • 31,968
  • 17
  • 99
  • 158
  • 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) – Sean Patrick Floyd May 03 '13 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. – Scott McIntyre May 20 '16 at 14:17
6

No but you can do it like this

new HashSet<String>(Arrays.asList("a", "b", ...));
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
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));
  }
Stuart Clark
  • 611
  • 8
  • 13
3

In guava you could use

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

newHashSet

OscarRyz
  • 196,001
  • 113
  • 385
  • 569
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...).

Philippe Gioseffi
  • 1,488
  • 3
  • 24
  • 41
-1
List<String> myList = new ArrayList<String>(Arrays.asList("a", "b"));
myList.add("c");
System.out.println(myList);

It worked without error