0 votes
1 view
in Java by (2.4k points)

I need to make a Set with initial values.

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

h.add("a");

h.add("b");

Is there a method to do this in one line of code? For instance, it's helpful for a final static field.

1 Answer

0 votes
by (21.1k points)

There's a one-liner that you can use but it's not very time efficient as you are converting an array and then converting to a list and using that list to create a set which can take some time. 

Here's the "Single Line" code:

Set<String> h = new HashSet<>(Arrays.asList("q", "w"));

I use this code like this while initializing static final sets:

public static final String[] SET_VALUES = new String[] { "q", "w" };

public static final Set<String> MY_SET = new HashSet<>(Arrays.asList(SET_VALUES));

If efficiency doesn't matter to you and you want your code less ugly, you can proceed with it.

...