Skip to content
Fix Code Error

How to initialize HashSet values by construction?

March 13, 2021 by Code Error
Posted By: Anonymous

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.

Solution

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.

Answered By: Anonymous

Related Articles

  • SQLException: No suitable Driver Found for…
  • HashSet vs. List performance
  • How can i display data from xml api in flutter?
  • Vue.JS & Spring Boot - Redirect to homepage on 404
  • I want to create a SQLite database like in the images how do…
  • Fastest way to iterate over all the chars in a String
  • How to filter a RecyclerView with a SearchView
  • How does PHP 'foreach' actually work?
  • For-each over an array in JavaScript
  • Django - update inline formset not updating

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to use a decimal range() step value?

Next Post:

How to solve PHP error ‘Notice: Array to string conversion in…’

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error