How can I initialize set in Java with initial values in a single line?

Currently, I create a Set and add values like this:

Set<String> h = new HashSet<String>();  
h.add("a");  
h.add("b");  

Is there a way to initialize a Set in one line? This would be particularly useful for defining a final static field.

Starting from Java 9, you can use Set.of(), which is concise and immutable.

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

:white_check_mark: Why This Works:

Creates an immutable set (modifications like add() will throw UnsupportedOperationException).

Very concise and efficient.

:x: Downside:

You cannot modify the set after creation.

Usage Example:

private static final Set<String> ALLOWED_VALUES = Set.of("apple", "banana", "cherry");

If you need a mutable set, wrapping Arrays.asList() with HashSet works well.

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

:white_check_mark: Why This Works:

Uses Arrays.asList() to create a fixed-size list, then wraps it in a HashSet, which is mutable.

Preserves uniqueness of elements.

:x: Downside:

A bit less efficient than Set.of() since it creates an intermediate list.

Usage Example:

Set<Integer> numbers = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
numbers.add(6); // Works fine

For flexibility, you can use Java Streams to collect values into a set.

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

:white_check_mark: Why This Works:

Uses Stream.of() to create a stream of elements and then collects them into a set.

Allows transformation of data before collecting.

:x: Downside:

Slightly less readable for simple cases.

Less efficient for small sets due to stream overhead.

Usage Example:

Set<Double> uniqueSquares = Stream.of(2.0, 3.0, 4.0)
                                  .map(x -> x * x)
                                  .collect(Collectors.toSet());