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.
If the contained type of the Set is an enumeration then there is java built factory method (since 1.5):
or
This is an elegant solution:
Collection literals were scheduled for Java 7, but didn't make it in. So nothing automatic yet.
You can use guava's
Sets
:Or you can use the following syntax, which will create an anonymous class, but it's hacky:
With Eclipse Collections there are a few different ways to initialize a
Set
containing the characters 'a' and 'b' in one statement. Eclipse Collections has containers for both object and primitive types, so I illustrated how you could use aSet<String>
orCharSet
in addition to mutable, immutable, synchronized and unmodifiable versions of both.Eclipse Collections is compatible with Java 5 - 8.
Note: I am a committer for Eclipse Collections.
In Java 8 I would use:
This gives you a mutable
Set
pre-initialized with "a" and "b". Note that while in JDK 8 this does return aHashSet
, the specification doesn't guarantee it, and this might change in the future. If you specifically want aHashSet
, do this instead: