java 11 toArray(IntFunction) default method & example

In this blog post, We are going to learn the Java 11 features - toArray(IntFunction) method.

Default Collection Method - toArray(IntFunction)

With Java 11 version, New default method toArray(IntFunction) is added in java.util.collection interface.

You can check my previous on default method.

This is used to return Array from a collection of objects dynamically.

During development, the Developer needs to convert Collection to Array types, This will ease and simplify the developer life

Signature

 default <T> T[] toArray(IntFunction<T[]> generator) {
        return toArray(generator.apply(0));
    }

This takes input as IntFunction - Functional interface which contains only one abstract method.

ToArray(IntFunction) Example

This example covers the following things

  • How to Convert List of Strings to Array of Strings?
  • How to Convert Set of Strings to Array of Strings?

List.of() and Set.of() methods introduced in Java 10, to create Unmodified collections

import java.util.Arrays;
import java.util.List;
import java.util.Set;

public class DefaultMethod {
    public static void main(String[] args) {
        final List<String> numbersList = List.of("One", "Two", "Three", "Four");
        System.out.println(Arrays.toString(numbersList.toArray(String[]::new)));
        final Set<String> setStrings = Set.of("Kiran", "John", "Frank", "Sai");
        System.out.println(Arrays.toString(setStrings.toArray(String[]::new)));

    }
}

Output:

[One, Two, Three, Four]
[Sai, John, Frank, Kiran]

Collection existing ToArray Methods

java Collection interface has already toArray() method. So, the Compiler is unable to decide when a null object passed and gives a compile error.

The method toArray(Object[]) is ambiguous for the type Set. The reason is compiler get ambiguous to choose from toArray(Object[]) and toArray(IntFunction[]) methods.

Instead of null,caste null like toArray((Object[])null). NullPointerException is always thrown for both of the methods.

Collection interface has the following overloaded methods, toArray(IntFunction) method is the default method and the remaining methods are not.

 default <T> T[] toArray(IntFunction<T[]> generator) {
        return toArray(generator.apply(0));
    }
    <T> T[] toArray(T[] a);
    Object[] toArray();

Conclusion

Learned default static method toArray in Collection in java10 with example