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.
There are a few ways:
Double brace initialization
This is a technique which creates an anonymous inner class which has an instance initializer which adds
String
s to itself when an instance is created:Keep in mind that this will actually create an new subclass of
HashSet
each time it is used, even though one does not have to explicitly write a new subclass.A utility method
Writing a method that returns a
Set
which is initialized with the desired elements isn't too hard to write:The above code only allows for a use of a
String
, but it shouldn't be too difficult to allow the use of any type using generics.Use a library
Many libraries have a convenience method to initialize collections objects.
For example, Google Collections has a
Sets.newHashSet(T...)
method which will populate aHashSet
with elements of a specific type.There is a shorthand that I use that is not very time efficient, but fits on a single line:
Again, this is not time efficient since you are constructing an array, converting to a list and using that list to create a set.
When initializing static final sets I usually write it like this:
Slightly less ugly and efficiency does not matter for the static initialization.
Just a small note, regardless of which of the fine approaches mentioned here you end up with, if this is a default that usually goes unmodified (like a default setting in a library you are creating), it is a good idea to follow this pattern:
The benefit depends on the number of instances you create of that class and how likely it's that defaults will be changed.
If you decide to follow this pattern, then you also get to pick the method of set initialization that's most readable. As the micro differences in efficiency between the different methods will probably not matter much as you will be initializing the set only once.
One of the most convenient ways is usage of generic Collections.addAll() method, which takes a collection and varargs:
With the release of java9 and the convenience factory methods this is possible in a cleaner way as:
A bit convoluted but works from Java 5:
Use a helper method to make it readable: