Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Three methods: 1 using toArray(T[] a) 2 using toArray() 3 using Java8 stream to convert collection objects into arrays

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

public class Test1 {
    public static void main(String[] args) {
        Set<Integer> allSet = new HashSet<>();
        allSet.add(1); allSet.add(2); allSet.add(3); allSet.add(4); allSet.add(5); allSet.add(6);
        printArray(toArray1(allSet));
        printArray(toArray2(allSet));
        printArray(toArray3(allSet));
    }

    private static void printArray(Object[] arr) {
        for (Object o : arr) {
            System.out.print(o + ",");
        }
        System.out.println();
    }

    ToArray (new Integer[]{})
    public static Integer[] toArray1(Set<Integer> allSet) {
        Integer[] arr = allSet.toArray(new Integer[]{});
        return arr;
    }

    ToArray (); // toArray()
    public static Integer[] toArray2(Set<Integer> allSet) {
        Object[] objArr = allSet.toArray();
        Integer[] intArr = new Integer[objArr.length];
        for (int i = 0; i < objArr.length; i++) {
            intArr[i] = (Integer) objArr[i];
        }
        return intArr;
    }

    // Method 3: Use Java8 stream to convert collection objects into arrays
    public static Integer[] toArray3(Set<Integer> allSet) {
        Integer[] arr = allSet.stream().toArray(Integer[]::new);
        returnarr; }}Copy the code