Java
Programming
Data Structures
Array
Set Conversion

How to convert an Array to a Set in Java

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Converting an array to a Set in Java is common when you want to remove duplicates, test membership quickly, or switch from ordered storage to uniqueness-based storage. The right conversion depends on whether you care about preserving insertion order, sorting the result, or handling primitive arrays rather than object arrays.

Core Sections

The most direct conversion for object arrays

For arrays of reference types such as String[] or Integer[], the standard pattern is to turn the array into a list and then construct a set from that list.

java
1import java.util.Arrays;
2import java.util.HashSet;
3import java.util.Set;
4
5public class ArrayToSetExample {
6    public static void main(String[] args) {
7        Integer[] numbers = {1, 2, 3, 3, 4, 4, 5};
8        Set<Integer> set = new HashSet<>(Arrays.asList(numbers));
9        System.out.println(set);
10    }
11}

This removes duplicates automatically because sets do not allow duplicate elements. If you do not care about order, HashSet is usually the simplest choice.

Preserve insertion order with LinkedHashSet

A HashSet does not preserve the original order of the array. If order matters, use LinkedHashSet.

java
1import java.util.Arrays;
2import java.util.LinkedHashSet;
3import java.util.Set;
4
5public class OrderedArrayToSet {
6    public static void main(String[] args) {
7        String[] values = {"b", "a", "b", "c"};
8        Set<String> set = new LinkedHashSet<>(Arrays.asList(values));
9        System.out.println(set);
10    }
11}

This keeps the first occurrence order from the array while still removing duplicates.

Sort the result with TreeSet

If you want uniqueness plus sorted output, use TreeSet instead.

java
1import java.util.Arrays;
2import java.util.Set;
3import java.util.TreeSet;
4
5public class SortedArrayToSet {
6    public static void main(String[] args) {
7        Integer[] values = {4, 2, 5, 2, 1};
8        Set<Integer> set = new TreeSet<>(Arrays.asList(values));
9        System.out.println(set);
10    }
11}

The tradeoff is that TreeSet sorts by natural ordering or a comparator, which changes iteration order and usually has different performance characteristics from HashSet.

Stream-based conversion in modern Java

If you are already using streams, collecting directly to a set can be more readable.

java
1import java.util.Arrays;
2import java.util.Set;
3import java.util.stream.Collectors;
4
5public class StreamArrayToSet {
6    public static void main(String[] args) {
7        String[] names = {"Ada", "Grace", "Ada"};
8        Set<String> set = Arrays.stream(names)
9                .collect(Collectors.toSet());
10        System.out.println(set);
11    }
12}

This is concise, but it is worth remembering that Collectors.toSet() does not promise a specific set implementation. If you care about order or type, collect into a concrete implementation explicitly.

java
Set<String> set = Arrays.stream(names)
        .collect(Collectors.toCollection(LinkedHashSet::new));

Primitive arrays need special handling

A common surprise is that Arrays.asList() does not behave the same way for primitive arrays such as int[]. Instead of creating a list of individual integers, it creates a list containing the entire array as one element.

java
1import java.util.Arrays;
2
3public class PrimitiveArrayPitfall {
4    public static void main(String[] args) {
5        int[] numbers = {1, 2, 3};
6        System.out.println(Arrays.asList(numbers).size());
7    }
8}

To convert a primitive array properly, use Arrays.stream() and then box the values.

java
1import java.util.Arrays;
2import java.util.Set;
3import java.util.stream.Collectors;
4
5public class PrimitiveArrayToSet {
6    public static void main(String[] args) {
7        int[] numbers = {1, 2, 2, 3};
8        Set<Integer> set = Arrays.stream(numbers)
9                .boxed()
10                .collect(Collectors.toSet());
11        System.out.println(set);
12    }
13}

That is the correct pattern for primitive arrays.

Common Pitfalls

  • Using HashSet when iteration order matters can produce unexpected ordering in later code.
  • Assuming Collectors.toSet() returns a specific implementation leads to brittle code.
  • Calling Arrays.asList() on a primitive array such as int[] does not produce a list of boxed elements.
  • Forgetting that duplicate removal is automatic can hide data issues if duplicates were actually meaningful.
  • Choosing TreeSet for conversion without intending to sort the values can silently change the result order.

Summary

  • For object arrays, new HashSet<>(Arrays.asList(array)) is the simplest array-to-set conversion.
  • Use LinkedHashSet if you need insertion order and TreeSet if you need sorted results.
  • Streams are concise, but Collectors.toSet() does not guarantee a particular set type.
  • Primitive arrays need Arrays.stream(...).boxed() before collection into a Set<Integer>.
  • Pick the set implementation based on uniqueness, ordering, and performance requirements rather than converting mechanically.

Course illustration
Course illustration

All Rights Reserved.