I need to create a Set
with initial values.
Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");
Is there a way to do this in one line of code? For instance, it's useful for a final static field.
I need to create a Set
with initial values.
Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");
Is there a way to do this in one line of code? For instance, it's useful for a final static field.
With Java 9 you can do the following:
and you'll get an immutable Set containing the elements. For details see the Oracle documentation of interface Set.
Using Java 10 (Unmodifiable Sets)
Here the collector would actually return the unmodifiable set introduced in Java 9 as evident from the statement
set -> (Set<T>)Set.of(set.toArray())
in the source code.Using Java 9 (Unmodifiable Sets)
Using Java 8 (Modifiable Sets)
Using Stream in Java 8.
Using Java 8 (Unmodifiable Sets)
Using Collections.unmodifiableSet - We can use
Collections.unmodifiableSet
as:But it looks slightly awkward and we can write our own collector like this:
And then use it as:
Using Collectors.collectingAndThen - Another approach is to use the method
Collectors.collectingAndThen
which lets us perform additional finishing transformations:If we only care about
Set
then we can also useCollectors.toSet()
in place ofCollectors.toCollection(HashSet::new)
.One point to note is that the method
Collections::unmodifiableSet
returns an unmodifiable view of the specified set, as per doc. An unmodifiable view collection is a collection that is unmodifiable and is also a view onto a backing collection. Note that changes to the backing collection might still be possible, and if they occur, they are visible through the unmodifiable view. But the methodCollectors.unmodifiableSet
returns truly immutable set in Java 10.(ugly) Double Brace Initialization without side effects:
But in some cases, if we mentioned that is a good smell to make final collections unmutable, it could be really useful:
Using Java 8 we can create
HashSet
as:And if we want unmodifiable set we can create a utility method as :
This method can be used as :
If you have only one initial value in set this would be enough:
Can use static block for initialization: