java 11 toArray(IntFunction) default method & example

java11 features - Default Collection Method toArray(IntFunction) 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


 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");
        final Set<String> setStrings = Set.of("Kiran", "John", "Frank", "Sai");



[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();


Learned default static method toArray in Collection in java10 with example

Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.