Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.5k 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 (46k 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.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 29, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
asked Jul 29, 2019 in Java by Suresh (3.4k points)
0 votes
1 answer

Browse Categories

...