2017  Kodetalk | Feedback | Privacy Policy | Terms | About

How to initialize HashSet values by construction?

I want to create a Set with initial values.

Set<String> h = new HashSet<String>();



Is there a way to do this in one command?


you can do this which fits on a single line:

Set<String> h = new HashSet<String>(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<String> MY_SET = new HashSet<String>(Arrays.asList(SET_VALUES));

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

Answer is