Friday, September 21, 2018

java 11 features - Default Collection Method toArray(IntFunction) example

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

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, Developer need 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 features  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 is
[One, Two, Three, Four]
[Sai, John, Frank, Kiran]

Collection existing ToArray Methods

Collection interface has already toArray() method, Compiler unable to decide when a null object is passed gives 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 following overloaded methods, toArray(IntFunction) method is the default method and remaining methods are not.

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

Related article


EmoticonEmoticon