Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize HashSet values by construction?

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.

like image 744
Serg Avatar asked Jan 11 '10 12:01

Serg


People also ask

How do you initialize a Set of values?

To initialize a Set with values, pass an iterable to the Set constructor. When an iterable is passed to the Set constructor, all elements get added to the new Set . The most common iterables to initialize a Set with are - array, string and another Set .

How do you create an empty HashSet in Java?

Using the clear() method only clears all the element from the set and not deletes the set. In other words, we can say that the clear() method is used to only empty an existing HashSet. Return Value: The function does not returns any value.

How is a HashSet defined in Java?

HashSet declaration In Java, a HashSet is declared using the keyword HashSet . This is followed by angle brackets < > that contain the data type of the data being stored.


1 Answers

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

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

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

like image 170
Gennadiy Avatar answered Sep 18 '22 12:09

Gennadiy