How to Initialize Set with Elements in Java


How can we initialize a Set with elements in Java?

Suppose we want to initialize the following Set with values.

Set<String> set;

1. Using Set constructor

We can create a list, and convert it to a set using the set constructor.

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

2. Using Set.of() (Java 9)

If we’re using Java 9, we can use Set.of().

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

Note that adding duplicate elements will throw IllegalArgumentException.

3. Using Streams (Java 8)

In Java 8, we can use the Stream API to collect the stream into a set.

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

We can specify the specific Set implementation as well.

Set<String> set = Stream.of("a", "b").collect(Collectors.toCollection(HashSet::new));

4. Using anonymous subclass (Java 8)

We can also create an anonymous subclass of HashSet that uses a static initializer to add elements to the set.

Set<String> set = new HashSet<>() {{
  add("a");
  add("b");
}};

5. Using Sets.newHashSet() (Guava)

If using Guava, we can use Sets.newHashSet().

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

6. Using Collections.singleton()

If we know our set will only have a single value, we can use Collections.singleton() to create an immutable set.

Set<String> immutableSet = Collections.singleton("a");