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.
You can do it in Java 6:
But why? I don't find it to be more readable than explicitly adding elements.
A generalization of coobird's answer's utility function for creating new
HashSet
s:I feel the most readable is to simply use google Guava:
The Builder pattern might be of use here. Today I had the same issue. where I needed Set mutating operations to return me a reference of the Set object, so I can pass it to super class constructor so that they too can continue adding to same set by in turn constructing a new StringSetBuilder off of the Set that the child class just built. The builder class I wrote looks like this (in my case it's a static inner class of an outer class, but it can be its own independent class as well):
Notice the
addAll()
andadd()
methods, which are Set returning counterparts ofSet.add()
andSet.addAll()
. Finally notice thebuild()
method, which returns a reference to the Set that the builder encapsulates. Below illustrates then how to use this Set builder: