Explain Codes LogoExplain Codes Logo

How to initialize HashSet values by construction?

java
prompt-engineering
best-practices
collections
Alex KataevbyAlex Kataev·Oct 8, 2024
TLDR

To initialize a HashSet instantly, you will need:

// yes, this is a speed run ⏩ Set<String> set = new HashSet<>(Arrays.asList("One", "Two", "And_a_half"));

Arrays.asList provides an efficient and clear method to set up a HashSet at construction stage.

Initialization methods and their pros and cons

For those static final fields

Keep things simple and efficient for static final fields:

// constants like the immortality of the cockroach 🪳 public static final Set<String> CONSTANT_SET = new HashSet<>(Arrays.asList("Roach1", "Roach2"));

Have a static array with predefined values? Utilize it!

// mix tape 🎵 preset values public static final String[] MY_JAMS = {"Track1", "Track2"}; public static final Set<String> MY_SET = new HashSet<>(Arrays.asList(MY_JAMS));

Leveraging Java 8 streams

Java 8 users, flex your stream muscles for dynamic set building:

// gotta catch 'em all! 🎣 Set<String> streamSet = Stream.of("Fish1", "Fish2").collect(Collectors.toCollection(HashSet::new));

Embracing the unchangeable: Java 9 or later

Want an immutable set in Java 9 or later? No worries, Set.of got you covered:

// they are set in stone ⛏ Set<String> immutableSet = Set.of("Stone1", "Stone2");

For Java 10 and later, the Stream API offers you unmodifiable sets:

// you can look but you can't touch 🖐🚫 Set<String> unmodifiableSet = Stream.of("Fragile1", "Fragile2") .collect(Collectors.toUnmodifiableSet());

Guava library for readability

For readable syntax, Google's Guava library introduces Sets.newHashSet:

// Google not just for searching cat videos 🐱‍👤 Set<String> guavaSet = Sets.newHashSet("Cat1", "Cat2");

Generics ensure type safety. Double-brace initialization may consume more memory though — keep in mind.

Guideline: best practices & common pitfalls

Be conscious of computational cost

In a non-static context, curb the extraneous conversions when initializing HashSet.

Control your mutability

The Stream.of() methods create a modifiable set, if immutable is what you seek, do this:

// the age-old "collect them then forbid modification" trick 🧙‍♂️ Set<String> collectedThenUnmodifiable = Stream.of("Magic1", "Magic2") .collect(Collectors.collectingAndThen(Collectors.toCollection(HashSet::new), Collections::unmodifiableSet));

Expert move: Using custom collectors

Seasoned users trying to impress? Try building your own collector for fun (and utility):

// trying to wizards your way 🧙‍♀️ Collector<String, ?, Set<String>> yourOwnCollector = Collector.of(HashSet::new, Set::add, (left, right) -> { left.addAll(right); return left; });

Type matters, specify it

// All HashSet matter ✊ Set<String> hashSet = Stream.of("Item1", "Item2").collect(Collectors.toCollection(HashSet::new));

Picture this:

🧺 Empty basket: [] 🧺 Basket with fruit: [🍏, 🍊, 🍌]

Just like out HashSet, our basket is ready for use! 🎉

Final pearls of wisdom

Generics are your friends

For efficient typing and to avoid warnings, specify the generic type:

// safety first 👷‍♀️ Set<String> safeSet = new HashSet<String>(Arrays.asList("Safe1", "Safe2"));

Immutable vs Unmodifiable

An unmodifiable set can’t be changed accidentally or intentionally — it’s really set in stone.

Consider memory costs

Double-brace initialization creates an anonymous class leading to unnecessary overhead. Avoid this if your code is performance-sensitive.