How do I convert Array to Set?

package org.kodejava.example.util;

import java.util.*;

public class ArrayToSetExample {
    public static void main(String[] args) {
        Integer[] numbers = {7, 7, 8, 9, 10, 8, 8, 9, 6, 5, 4};

        // To convert an array into a java.util.Set firstly we need to convert the
        // array into a java.util.List using the Arrays.asList() method. With the
        // List object created we can instantiate a new java.util.HashSet and pass
        // the list as the constructor parameter.
        List<Integer> numberList = Arrays.asList(numbers);
        Set<Integer> numberSet = new HashSet<>(numberList);

        // Or we can simply combine the line above into single line.
        Set<Integer> anotherNumberSet = new HashSet<>(Arrays.asList(numbers));

        // Display what we get in the set using iterator.
        for (Iterator<Integer> iterator = numberSet.iterator(); iterator.hasNext(); ) {
            Integer number =;
            System.out.print(number + ", ");

        // Display what we get in the set using for-each.
        for (Integer number : anotherNumberSet) {
            System.out.print(number + ", ");

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.