how to convert hashset to array in java code example

Example 1: convert hashset to int array java

import java.util.Arrays;
import java.util.Set;
import java.util.HashSet;
class Main
{
    // Program to convert set of integer to array of int in Java
    public static void main(String args[])
    {
        Set<Integer> ints = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
        int[] primitive = ints.stream()
                            .mapToInt(Integer::intValue)
                            .toArray();
        System.out.println(Arrays.toString(primitive));
    }
}

Example 2: convert hashset to array

//	First of all, you shouldn't use raw types.
//	Use :
	Set<Integer> set = new HashSet<>();
	set.add(4);
	set.add(1);
//	Then convert to array :
	Integer[] arr = x.toArray(new Integer[set.size()]);
//	Using x.toArray() would give you an Object[].

Tags:

Java Example