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.
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With