Explain Codes LogoExplain Codes Logo

How to convert an Array to a Set in Java

java
prompt-engineering
java-8
collections
Alex KataevbyAlex Kataev·Sep 27, 2024
TLDR

Quick and dirty, turn an array into a set with new HashSet<>(Arrays.asList(yourArray)). Removes duplicate elements like your mom scrubbing out stains.

Integer[] primeNumbers = {2, 3, 5, 2, 3}; Set<Integer> primeSet = new HashSet<>(Arrays.asList(primeNumbers)); // Smells fresh! Now it's {2, 3, 5}, duplicates are gone.

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:

String[] toys = {"Lego", "Playmobil", "Lego"}; Set<String> toySet = Set.of(toys); // Immovable like a stubborn mule

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:

var petSet = Set.of("Dog", "Cat", "Parrot");

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.

String[] redundantData = {"Spam", "Ham", "Spam"}; Set<String> tidyDataSet = Set.copyOf(Arrays.asList(redundantData));

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:

int[] lotteryNumbers = {7, 11, 42, 7}; Set<Integer> luckyNumbers = Arrays.stream(lotteryNumbers).boxed().collect(Collectors.toSet()); // [7, 11, 42] - Looks like duplicate '7' bought the farm

Google Guava also throws an interesting party. It snaps your primitive arrays into a HashSet in no time:

int[] grades = {1, 2, 3, 4}; Set<Integer> gradeSet = Sets.newHashSet(Ints.asList(grades));

The Guava documentation is your ultimate party guide, party animal!

Java 8 style: All jazzed about Streams

String[] planets = {"Earth", "Mars", "Saturn", "Earth"}; Set<String> planetSet = Arrays.stream(planets).collect(Collectors.toSet()); // Earth Mars Saturn. Earth's twin left in the cold.

To convert a primitive array to a Set in Java 8, remember to box the primitives:

int[] randomNumbers = {1, 2, 3, 2}; Set<Integer> numberSet = Arrays.stream(randomNumbers).boxed().collect(Collectors.toSet()); // {1, 2, 3}. Keeping duplicates away since 2014!

Functional and sleek, showcasing the charisma of Java Streams.

Adding to Set efficiently

Adding more elements? Collections.addAll is your genie:

Set<String> set = new HashSet<>(); String[] extras = {"Extra1", "Extra2", "Extra3"}; Collections.addAll(set, extras);

Poof! All array elements join the party in the blink of an eye!

Loop conversion in older Java

String[] heroes = {"Batman", "Superman", "Batman"}; Set<String> heroSet = new HashSet<>(); for (String hero: heroes) { heroSet.add(hero); // Batman: Why do we have two Batmen? // Alfred: Because he's Batman, sir! }

Riding the for-each loop bandwagon, old-fashioned yet reliable.

String arrays into Sets

String[] coolCars = {"Tesla", "Ford Mustang", "Tesla"}; Set<String> carSet = Arrays.stream(coolCars).collect(Collectors.toSet()); System.out.println(carSet); // Elon Musk: Why do we have two Teslas? // Intern: One for Earth, one for Mars, sir!

This resulting Set looks like it's got its elements in order, but beware! Order's not always a thing with HashSet.