HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaCritical

How to initialize HashSet values by construction?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
hashsethowinitializevaluesconstruction

Problem

I need to create a Set with initial values.

Set h = new HashSet();
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.

Solution

There is a shorthand that I use that is not very time efficient, but fits on a single line:

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


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:

public static final String[] SET_VALUES = new String[] { "a", "b" };
public static final Set MY_SET = new HashSet<>(Arrays.asList(SET_VALUES));


Slightly less ugly and efficiency does not matter for the static initialization.

Code Snippets

Set<String> h = new HashSet<>(Arrays.asList("a", "b"));
public static final String[] SET_VALUES = new String[] { "a", "b" };
public static final Set<String> MY_SET = new HashSet<>(Arrays.asList(SET_VALUES));

Context

Stack Overflow Q#2041778, score: 1190

Revisions (0)

No revisions yet.