Conversion Between Array and Set in Java

In this short article, we will write a Java program to convert Array to Set and vice versa.

Convert Array to a Set

Let's write a Java program to convert Array to Set:
package net.javaguides.hibernate;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class ConvertArrayToSetExample {
    public static void main(String[] args) {

        Integer[] sourceArray = {
            0,
            1,
            2,
            3,
            4,
            5
        };

        // convert Array to Set
        Set < Integer > targetSet = new HashSet < Integer > (Arrays.asList(sourceArray));

        // print set
        targetSet.forEach(value - > System.out.println(value));
    }
}
Output:
0
1
2
3
4
5

Convert Set to Array

Let's write a Java program to convert Set to Array:
package net.javaguides.hibernate;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class ConvertSetToArrayExample {
    public static void main(String[] args) {

        Set < Integer > sourceSet = new HashSet < > ();
        sourceSet.add(0);
        sourceSet.add(1);
        sourceSet.add(2);
        sourceSet.add(3);
        sourceSet.add(4);
        sourceSet.add(5);

        Integer[] targetArray = sourceSet.toArray(new Integer[sourceSet.size()]);

        System.out.println(Arrays.toString(targetArray));
    }
}
Output:
[0, 1, 2, 3, 4, 5]

Similar Collections Examples [Snippet]

Comments