HashSet toArray(IntFunction) in Java

toArray(IntFunction): This method is available in java.util.HashSet class of Java.

Syntax:

<K> K[] java.util.Collection.toArray(IntFunction<K[]> generator)

This method takes one argument. This method returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.

Parameters: One parameter is required for this method.

generator: a function that produces a new array of the desired type and the provided length.

Returns: an array containing all of the elements in this collection.

Throws:

1. ArrayStoreException - if the runtime type of any element in this collection is not assignable to the runtime component type of the generated array.

2. NullPointerException - if the generator function is null.

Approach 1: When no exception

Java

import java.util.Arrays;
import java.util.HashSet;
import java.util.function.IntFunction;

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

        HashSet<String> hashSet = new HashSet<String>();

        hashSet.add("Hello");
        hashSet.add("Java");
        hashSet.add("C++");
        hashSet.add("Hello");

        IntFunction<String[]> intFunction =
new IntFunction<String[]>() {

            @Override
            public String[] apply(int value) {
                String[] string = { "Hello", "C++" };
                return string;

            }
        };

        System.out.println(Arrays.toString(hashSet.
toArray(intFunction)));
    }
}

Output:

[Java, C++, Hello]


Approach 2: NullPointerException

Java

import java.util.Arrays;
import java.util.HashSet;
import java.util.function.IntFunction;

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

        HashSet<String> hashSet = new HashSet<String>();

        hashSet.add("Hello");
        hashSet.add("Java");
        hashSet.add("C++");
        hashSet.add("Hello");

        IntFunction<String[]> intFunction = null;

        System.out.println(Arrays.toString(hashSet.
toArray(intFunction)));
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.function.IntFunction.apply(int)" because "generator" is null at java.base/java.util.Collection.toArray(Collection.java:413)


No comments:

Post a Comment