How to convert an Array to a Set in Java
Quick and dirty, turn an array into a set with new HashSet<>(Arrays.asList(yourArray))
. Removes duplicate elements like your mom scrubbing out stains.
A shining HashSet
is born with the elements of your array, brought into this world by the stork, aka Arrays.asList
.
Choosing Set in modern Java
When you're in a candy store, choose wisely. In the world of Java 9 or newer, there are treats to make an array a set:
Set.of
gives you an immutable set. It's like a dog with no legs: it won't run away, but don't try to get it to fetch. Trying to add or remove elements will get you a stern UnsupportedOperationException.
For the Java 10 hipsters, no need to specify the type. It's like mind reading:
Local variable type inference is the magician's trick that lets Java guess that petSet
is a Set<String>
. Sleight of hand, anyone?
Duplicate handling and immutability
What if your array is like the movie "Groundhog Day", full of duplicates? Set.copyOf
can intervene and gift you an immutable snapshot of these moments, sans duplicates.
Sick and tired of mutable sets? Move to immutable sets listed in the brochures of the Java Collections Framework.
Don't exclude the primitives
Playing with primitive arrays? No worries, use boxed()
method to get them to mingle with the civilized society of wrapper classes:
Google Guava also throws an interesting party. It snaps your primitive arrays into a HashSet
in no time:
The Guava documentation is your ultimate party guide, party animal!
Java 8 style: All jazzed about Streams
To convert a primitive array to a Set
in Java 8, remember to box the primitives:
Functional and sleek, showcasing the charisma of Java Streams.
Adding to Set efficiently
Adding more elements? Collections.addAll
is your genie:
Poof! All array elements join the party in the blink of an eye!
Loop conversion in older Java
Riding the for-each loop bandwagon, old-fashioned yet reliable.
String arrays into Sets
This resulting Set
looks like it's got its elements in order, but beware! Order's not always a thing with HashSet
.
Was this article helpful?